Exemple #1
0
        private void button6_Click(object sender, EventArgs e)
        {
            PCFExport pcfExporter = new PCFExport();
            Result    result      = Result.Failed;

            if (iv.ExportAllOneFile || iv.ExportSpecificPipeLine || iv.ExportSelection)
            {
                result = pcfExporter.ExecuteMyCommand(_uiapp, ref _message);
            }
            else if (iv.ExportAllSepFiles)
            {
                foreach (string name in pipeLinesAbbreviations)
                {
                    iv.SysAbbr = name;
                    result     = pcfExporter.ExecuteMyCommand(_uiapp, ref _message);
                }
            }

            if (result == Result.Succeeded)
            {
                BuildingCoderUtilities.InfoMsg("PCF data exported successfully!");
            }
            if (result == Result.Failed)
            {
                BuildingCoderUtilities.InfoMsg("PCF data export failed for some reason.");
            }
        }
        private void Button6_Click(object sender, EventArgs e)
        {
            NTR_Exporter exporter = new NTR_Exporter();

            Result result = Result.Failed;

            if (iv.ExportAllOneFile || iv.ExportSpecificPipeLine || iv.ExportSelection)
            {
                result = exporter.ExportNtr(_commandData);
            }
            else if (iv.ExportAllSepFiles)
            {
                foreach (string name in pipeLinesAbbreviations)
                {
                    iv.SysAbbr = name;
                    result     = exporter.ExportNtr(_commandData);
                }
            }

            if (result == Result.Succeeded)
            {
                BuildingCoderUtilities.InfoMsg("NTR data exported successfully!");
            }
            if (result == Result.Failed)
            {
                BuildingCoderUtilities.InfoMsg("NTR data export failed for some reason.");
            }
        }
Exemple #3
0
        internal Result ExecuteMyCommand(UIApplication uiApp, ref string msg)
        {
            // UIApplication uiApp = commandData.Application;
            Document doc = uiApp.ActiveUIDocument.Document;

            //Call the method to delete parameters
            try
            {
                Transaction trans = new Transaction(doc, "Delete PCF parameters");
                trans.Start();
                foreach (pdef parameter in new plst().LPAll.ToList())
                {
                    RemoveSharedParameterBinding(doc.Application, parameter.Name, parameter.Type);
                }
                trans.Commit();
                BuildingCoderUtilities.InfoMsg(sbFeedback.ToString());
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return(Result.Cancelled);
            }

            catch (Exception ex)
            {
                msg = ex.Message;
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     iv.ExcelSheet = (string)comboBox1.SelectedItem;
     //mySettings.Default.excelWorksheetSelectedName = iv.ExcelSheet;
     DATA_TABLE = DATA_SET.Tables[iv.ExcelSheet];
     ParameterData.parameterNames = null;
     ParameterData.parameterNames = (from dc in DATA_TABLE.Columns.Cast <DataColumn>() select dc.ColumnName).ToList();
     ParameterData.parameterNames.RemoveAt(0);
     BuildingCoderUtilities.InfoMsg("Following parameters will be initialized:\n" + string.Join("\n", ParameterData.parameterNames.ToArray()));
 }
Exemple #5
0
        private void button9_Click(object sender, EventArgs e)
        {
            ExportParameters EP = new ExportParameters();
            var output          = EP.ExecuteMyCommand(_uiapp);

            if (output == Result.Succeeded)
            {
                BuildingCoderUtilities.InfoMsg("Elements exported to EXCEL successfully!");
            }
            else if (output == Result.Failed)
            {
                BuildingCoderUtilities.InfoMsg("Element export to EXCEL failed for some reason.");
            }
        }
Exemple #6
0
        private void button8_Click(object sender, EventArgs e)
        {
            ScheduleCreator SC     = new ScheduleCreator();
            var             output = SC.CreateAllItemsSchedule(_uidoc);

            if (output == Result.Succeeded)
            {
                BuildingCoderUtilities.InfoMsg("Schedules created successfully!");
            }
            else if (output == Result.Failed)
            {
                BuildingCoderUtilities.InfoMsg("Schedule creation failed for some reason.");
            }
        }
Exemple #7
0
        //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 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);
        }
Exemple #9
0
        internal Result CreatePipelineBindings(UIApplication uiApp, ref string msg)
        {
            // UIApplication uiApp = commandData.Application;
            Document    doc = uiApp.ActiveUIDocument.Document;
            Application app = doc.Application;

            Autodesk.Revit.Creation.Application ca = app.Create;

            Category pipelineCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_PipingSystem);

            CategorySet catSet = ca.NewCategorySet();

            catSet.Insert(pipelineCat);

            string ExecutingAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string oriFile  = app.SharedParametersFilename;
            string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()) + ".txt";

            using (File.Create(tempFile)) { }
            uiApp.Application.SharedParametersFilename = tempFile;
            app.SharedParametersFilename = tempFile;
            DefinitionFile file   = app.OpenSharedParameterFile();
            var            groups = file.Groups;
            int            count  = 0;

            StringBuilder sbFeedback = new StringBuilder();

            //Parameter query
            var query = from p in new plst().LPAll
                        where (p.Domain == "PIPL" || p.Name == "PCF_PIPL_EXCL") && p.ExportingTo != "LDT"
                        select p;

            //Create parameter bindings
            Transaction trans = new Transaction(doc, "Bind PCF parameters");

            trans.Start();

            foreach (pdef parameter in query.ToList())
            {
                count++;

                ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions(parameter.Name, parameter.Type)
                {
                    GUID = parameter.Guid
                };

                string             tempName = "TemporaryDefinitionGroup" + count;
                var                tempGr   = groups.Create(tempName);
                var                tempDefs = tempGr.Definitions;
                ExternalDefinition def      = tempDefs.Create(options) as ExternalDefinition;

                BindingMap map     = doc.ParameterBindings;
                Binding    binding = app.Create.NewTypeBinding(catSet);

                if (map.Contains(def))
                {
                    sbFeedback.Append("Parameter " + parameter.Name + " already exists.\n");
                }
                else
                {
                    map.Insert(def, binding, InputVars.PCF_BUILTIN_GROUP_NAME);
                    if (map.Contains(def))
                    {
                        sbFeedback.Append("Parameter " + parameter.Name + " added to project.\n");
                    }
                    else
                    {
                        sbFeedback.Append("Creation of parameter " + parameter.Name + " failed for some reason.\n");
                    }
                }
            }
            trans.Commit();
            BuildingCoderUtilities.InfoMsg(sbFeedback.ToString());
            File.Delete(tempFile);

            app.SharedParametersFilename = oriFile;

            return(Result.Succeeded);
        }
Exemple #10
0
        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);
        }
Exemple #11
0
        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);
        }
Exemple #12
0
        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);
        }
        //private UIDocument _uiDoc;
        public Result CreateAllItemsSchedule(UIDocument uiDoc)
        {
            try
            {
                Document doc = uiDoc.Document;
                FilteredElementCollector sharedParameters = new FilteredElementCollector(doc);
                sharedParameters.OfClass(typeof(SharedParameterElement));

                #region Debug

                ////Debug
                //StringBuilder sbDev = new StringBuilder();
                //var list = new ParameterDefinition().ElementParametersAll;
                //int i = 0;

                //foreach (SharedParameterElement sp in sharedParameters)
                //{
                //    sbDev.Append(sp.GuidValue + "\n");
                //    sbDev.Append(list[i].Guid.ToString() + "\n");
                //    i++;
                //    if (i == list.Count) break;
                //}
                ////sbDev.Append( + "\n");
                //// Clear the output file
                //File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "\\Dev.pcf", new byte[0]);

                //// Write to output file
                //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "\\Dev.pcf"))
                //{
                //    w.Write(sbDev);
                //    w.Close();
                //}

                #endregion

                Transaction t = new Transaction(doc, "Create items schedules");
                t.Start();

                #region Schedule ALL elements
                ViewSchedule schedAll = ViewSchedule.CreateSchedule(doc, ElementId.InvalidElementId,
                                                                    ElementId.InvalidElementId);
                schedAll.Name = "PCF - ALL Elements";
                schedAll.Definition.IsItemized = false;

                IList <SchedulableField> schFields = schedAll.Definition.GetSchedulableFields();

                foreach (SchedulableField schField in schFields)
                {
                    if (schField.GetName(doc) != "Family and Type")
                    {
                        continue;
                    }
                    ScheduleField          field          = schedAll.Definition.AddField(schField);
                    ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                    schedAll.Definition.AddSortGroupField(sortGroupField);
                }

                string curUsage  = "U";
                string curDomain = "ELEM";
                var    query     = from p in new plst().LPAll where p.Usage == curUsage && p.Domain == curDomain select p;

                foreach (pdef pDef in query.ToList())
                {
                    SharedParameterElement parameter = (from SharedParameterElement param in sharedParameters
                                                        where param.GuidValue.CompareTo(pDef.Guid) == 0
                                                        select param).First();
                    SchedulableField queryField = (from fld in schFields where fld.ParameterId.IntegerValue == parameter.Id.IntegerValue select fld).First();

                    ScheduleField field = schedAll.Definition.AddField(queryField);
                    if (pDef.Name != "PCF_ELEM_TYPE")
                    {
                        continue;
                    }
                    ScheduleFilter filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.HasParameter);
                    schedAll.Definition.AddFilter(filter);
                }
                #endregion

                #region Schedule FILTERED elements
                ViewSchedule schedFilter = ViewSchedule.CreateSchedule(doc, ElementId.InvalidElementId,
                                                                       ElementId.InvalidElementId);
                schedFilter.Name = "PCF - Filtered Elements";
                schedFilter.Definition.IsItemized = false;

                schFields = schedFilter.Definition.GetSchedulableFields();

                foreach (SchedulableField schField in schFields)
                {
                    if (schField.GetName(doc) != "Family and Type")
                    {
                        continue;
                    }
                    ScheduleField          field          = schedFilter.Definition.AddField(schField);
                    ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                    schedFilter.Definition.AddSortGroupField(sortGroupField);
                }

                foreach (pdef pDef in query.ToList())
                {
                    SharedParameterElement parameter = (from SharedParameterElement param in sharedParameters
                                                        where param.GuidValue.CompareTo(pDef.Guid) == 0
                                                        select param).First();
                    SchedulableField queryField = (from fld in schFields where fld.ParameterId.IntegerValue == parameter.Id.IntegerValue select fld).First();

                    ScheduleField field = schedFilter.Definition.AddField(queryField);
                    if (pDef.Name != "PCF_ELEM_TYPE")
                    {
                        continue;
                    }
                    ScheduleFilter filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.HasParameter);
                    schedFilter.Definition.AddFilter(filter);
                    filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.NotEqual, "");
                    schedFilter.Definition.AddFilter(filter);
                }
                #endregion

                #region Schedule Pipelines
                ViewSchedule schedPipeline = ViewSchedule.CreateSchedule(doc, new ElementId(BuiltInCategory.OST_PipingSystem), ElementId.InvalidElementId);
                schedPipeline.Name = "PCF - Pipelines";
                schedPipeline.Definition.IsItemized = false;

                schFields = schedPipeline.Definition.GetSchedulableFields();

                foreach (SchedulableField schField in schFields)
                {
                    if (schField.GetName(doc) != "Family and Type")
                    {
                        continue;
                    }
                    ScheduleField          field          = schedPipeline.Definition.AddField(schField);
                    ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                    schedPipeline.Definition.AddSortGroupField(sortGroupField);
                }

                curDomain = "PIPL";
                foreach (pdef pDef in query.ToList())
                {
                    SharedParameterElement parameter = (from SharedParameterElement param in sharedParameters
                                                        where param.GuidValue.CompareTo(pDef.Guid) == 0
                                                        select param).First();
                    SchedulableField queryField = (from fld in schFields where fld.ParameterId.IntegerValue == parameter.Id.IntegerValue select fld).First();
                    schedPipeline.Definition.AddField(queryField);
                }
                #endregion

                t.Commit();

                sharedParameters.Dispose();

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                BuildingCoderUtilities.InfoMsg(e.Message);
                return(Result.Failed);
            }
        }
Exemple #14
0
        public Result Execute(ExternalCommandData commandData, ref string msg, ElementSet elements)
        {
            UIApplication uiApp    = commandData.Application;
            Document      doc      = uiApp.ActiveUIDocument.Document;
            UIDocument    uidoc    = uiApp.ActiveUIDocument;
            Transaction   trans    = new Transaction(doc, "Set System");
            MEPModel      mepModel = null;

            trans.Start();
            try
            {
                //Select Element to provide a system
                //Pipe type to restrict selection of tapping element
                Type t = typeof(Pipe);

                //Select tap element
                Element systemDonor = BuildingCoderUtilities.SelectSingleElementOfType(uidoc, t, "Select a pipe in desired system.", false);

                if (systemDonor == null)
                {
                    throw new Exception("System assignment cancelled!");
                }

                //Select Element to add to system
                Element elementToAdd = BuildingCoderUtilities.SelectSingleElement(uidoc, "Select support to add to system.");

                if (elementToAdd == null)
                {
                    throw new Exception("System assignment cancelled!");
                }

                //Cast the selected element to Pipe
                Pipe pipe = (Pipe)systemDonor;
                //Get the pipe type from pipe
                ElementId pipeTypeId = pipe.PipeType.Id;

                //Get system type from pipe
                ConnectorSet pipeConnectors = pipe.ConnectorManager.Connectors;
                Connector    pipeConnector  = (from Connector c in pipeConnectors where true select c).FirstOrDefault();
                ElementId    pipeSystemType = pipeConnector.MEPSystem.GetTypeId();

                //Collect levels and select one level
                FilteredElementCollector collector   = new FilteredElementCollector(doc);
                ElementClassFilter       levelFilter = new ElementClassFilter(typeof(Level));
                ElementId levelId = collector.WherePasses(levelFilter).FirstElementId();

                //Get the connector from the support
                FamilyInstance familyInstanceToAdd = (FamilyInstance)elementToAdd;
                ConnectorSet   connectorSetToAdd   = new ConnectorSet();
                mepModel          = familyInstanceToAdd.MEPModel;
                connectorSetToAdd = mepModel.ConnectorManager.Connectors;
                if (connectorSetToAdd.IsEmpty)
                {
                    throw new Exception(
                              "The support family lacks a connector. Please read the documentation for correct procedure of setting up a support element.");
                }
                Connector connectorToConnect =
                    (from Connector c in connectorSetToAdd where true select c).FirstOrDefault();

                //Create a point in space to connect the pipe
                XYZ direction    = connectorToConnect.CoordinateSystem.BasisZ.Multiply(2);
                XYZ origin       = connectorToConnect.Origin;
                XYZ pointInSpace = origin.Add(direction);

                //Create the pipe
                Pipe newPipe = Pipe.Create(doc, pipeTypeId, levelId, connectorToConnect, pointInSpace);

                //Change the pipe system type to match the picked pipe (it is not always matching)
                newPipe.SetSystemType(pipeSystemType);

                trans.Commit();

                trans.Start("Delete the pipe");

                //Delete the pipe
                doc.Delete(newPipe.Id);

                trans.Commit();
            }

            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                trans.RollBack();
                return(Result.Cancelled);
            }

            catch (Exception ex)
            {
                trans.RollBack();
                msg = ex.Message;
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
Exemple #15
0
        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);
        }
Exemple #16
0
        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();
            //}
        }
Exemple #17
0
        internal Result CreatePipelineBindings(UIApplication uiApp, ref string msg)
        {
            // UIApplication uiApp = commandData.Application;
            Document    doc = uiApp.ActiveUIDocument.Document;
            Application app = doc.Application;

            Autodesk.Revit.Creation.Application ca = app.Create;

            Category pipelineCat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_PipingSystem);

            CategorySet catSet = ca.NewCategorySet();

            catSet.Insert(pipelineCat);

            string ExecutingAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string oriFile  = app.SharedParametersFilename;
            string tempFile = ExecutingAssemblyPath + "Temp.txt";

            StringBuilder sbFeedback = new StringBuilder();

            //Parameter query
            var query = from p in new plst().LPAll
                        where p.Domain == "PIPL" ||
                        p.Name == "CII_PIPL_EXCL"
                        select p;

            //Create parameter bindings
            try
            {
                Transaction trans = new Transaction(doc, "Bind PCF parameters");
                trans.Start();
                foreach (pdef parameter in query.ToList())
                {
                    using (File.Create(tempFile)) { }
                    app.SharedParametersFilename = tempFile;
                    ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions(parameter.Name, parameter.Type)
                    {
                        GUID = parameter.Guid
                    };
                    ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create("TemporaryDefinitionGroup").Definitions.Create(options) as ExternalDefinition;

                    BindingMap map     = doc.ParameterBindings;
                    Binding    binding = app.Create.NewTypeBinding(catSet);

                    if (map.Contains(def))
                    {
                        sbFeedback.Append("Parameter " + parameter.Name + " already exists.\n");
                    }
                    else
                    {
                        map.Insert(def, binding, InputVars.PCF_BUILTIN_GROUP_NAME);
                        if (map.Contains(def))
                        {
                            sbFeedback.Append("Parameter " + parameter.Name + " added to project.\n");
                        }
                        else
                        {
                            sbFeedback.Append("Creation of parameter " + parameter.Name + " failed for some reason.\n");
                        }
                    }
                    File.Delete(tempFile);
                }
                trans.Commit();
                BuildingCoderUtilities.InfoMsg(sbFeedback.ToString());
            }

            catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); }

            catch (Exception ex)
            {
                msg = ex.Message;
                return(Result.Failed);
            }

            app.SharedParametersFilename = oriFile;

            return(Result.Succeeded);
        }
        public void AnalyzeSystem()
        {
            //Deviously hard to follow (and debug) code be here
            //Start analysis
            var openEnds = detectOpenEnds(Model);

            Connector        To          = null;
            Connector        From        = null;
            Node             FromNode    = null;
            Node             ToNode      = null;
            Element          curElem     = null;
            AnalyticElement  curAElem    = null;
            AnalyticSequence curSequence = null;

            bool continueSequence = false;

            IList <Connector> branchEnds = new List <Connector>();

            for (int i = 0; i < Model.AllElements.Count; i++)
            {
                if (!continueSequence)
                {
                    if (branchEnds.Count > 0)
                    {
                        From       = branchEnds.FirstOrDefault();
                        branchEnds = branchEnds.ExceptWhere(c => c.Equalz(From, _1mmTol)).ToList();
                        FromNode   = (from Node n in Model.AllNodes
                                      where n.PreviousCon != null && n.PreviousCon.Equalz(From, _1mmTol)
                                      select n).FirstOrDefault();
                        FromNode.NextCon = From;
                    }
                    else
                    {
                        From             = openEnds.FirstOrDefault();
                        openEnds         = openEnds.ExceptWhere(c => c.Equalz(From, _1mmTol)).ToList();
                        FromNode         = new Node();
                        FromNode.NextCon = From;
                        Model.AllNodes.Add(FromNode);



                        curSequence = new AnalyticSequence();
                    }

                    ToNode = new Node();

                    curElem  = From.Owner;
                    curAElem = new AnalyticElement(curElem);

                    continueSequence = true;
                }

                switch (curElem)
                {
                case Pipe pipe:

                    To = (from Connector c in pipe.ConnectorManager.Connectors     //End of the host/dummy pipe
                          where c.Id != From.Id && (int)c.ConnectorType == 1
                          select c).FirstOrDefault();

                    //Test if the ToNode already exists
                    //TODO: This test must be copied to all other elements
                    Node existingToNode = (from Node n in Model.AllNodes
                                           where
                                           (n.PreviousCon != null && n.PreviousCon.Equalz(To, _1mmTol)) ||
                                           (n.NextCon != null && n.NextCon.Equalz(To, _1mmTol))
                                           select n).FirstOrDefault();

                    if (existingToNode != null)
                    {
                        ToNode = existingToNode;
                        if (ToNode.PreviousCon == null)
                        {
                            ToNode.PreviousCon = To;
                        }
                        else if (ToNode.NextCon == null)
                        {
                            ToNode.NextCon = To;
                        }
                    }
                    else
                    {
                        ToNode.PreviousCon = To;
                        Model.AllNodes.Add(ToNode);
                    }

                    curAElem.From = FromNode;
                    curAElem.To   = ToNode;

                    //Assign correct element type to analytic element
                    curAElem.Type = ElemType.Pipe;

                    curSequence.Sequence.Add(curAElem);

                    break;

                case FamilyInstance fi:
                    Cons cons = MepUtils.GetConnectors(fi);
                    int  cat  = fi.Category.Id.IntegerValue;
                    switch (cat)
                    {
                    case (int)BuiltInCategory.OST_PipeFitting:
                        var mf       = fi.MEPModel as MechanicalFitting;
                        var partType = mf.PartType;
                        switch (partType)
                        {
                        case PartType.Elbow:
                            //First Analytic Element
                            XYZ elbowLoc = ((LocationPoint)fi.Location).Point;
                            ToNode.PreviousLoc = elbowLoc;         //The node has only element Location point defining it -
                            ToNode.NextLoc     = elbowLoc;         //and not two adjacent Connectors as element connection nodes
                            ToNode.Type        = ElemType.Elbow;
                            Model.AllNodes.Add(ToNode);

                            curAElem.From = FromNode;
                            curAElem.To   = ToNode;

                            curAElem.Type = ElemType.Elbow;

                            curAElem.AnalyzeBend();

                            curSequence.Sequence.Add(curAElem);

                            //Second Analytic Element
                            //First determine the To connector
                            To = (from Connector c in MepUtils.GetALLConnectorsFromElements(curElem)
                                  where c.Id != From.Id
                                  select c).FirstOrDefault();

                            FromNode = ToNode;             //Switch to next element
                            ToNode   = new Node();
                            Model.AllNodes.Add(ToNode);
                            ToNode.PreviousCon = To;
                            curAElem           = new AnalyticElement(curElem);
                            curAElem.From      = FromNode;
                            curAElem.To        = ToNode;

                            curAElem.Type = ElemType.Pipe;

                            curSequence.Sequence.Add(curAElem);
                            break;

                        case PartType.Tee:
                            //Junction logic
                            Node primNode = null;
                            Node secNode  = null;
                            Node tertNode = null;

                            //First analytic element
                            XYZ teeLoc = ((LocationPoint)fi.Location).Point;
                            ToNode.PreviousLoc = teeLoc;         //The node has only element Location point defining it -
                            ToNode.NextLoc     = teeLoc;         //and not two adjacent Connectors as element connection nodes
                            ToNode.Type        = ElemType.Tee;
                            Model.AllNodes.Add(ToNode);

                            curAElem.From = FromNode;
                            curAElem.To   = ToNode;

                            curAElem.Type = ElemType.Tee;

                            curSequence.Sequence.Add(curAElem);

                            //Logic to return correct node to next element
                            if (From.GetMEPConnectorInfo().IsPrimary)
                            {
                                primNode = FromNode;
                            }
                            else if (From.GetMEPConnectorInfo().IsSecondary)
                            {
                                secNode = FromNode;
                            }
                            else
                            {
                                tertNode = FromNode;
                            }

                            //From node is common for next two elements
                            FromNode = ToNode;

                            //Second Analytic Element
                            if (From.GetMEPConnectorInfo().IsPrimary)
                            {
                                To = cons.Secondary;
                            }
                            else if (From.GetMEPConnectorInfo().IsSecondary)
                            {
                                To = cons.Primary;
                            }
                            else
                            {
                                To = cons.Primary;
                            }

                            ToNode = new Node();
                            Model.AllNodes.Add(ToNode);
                            ToNode.PreviousCon = To;
                            curAElem           = new AnalyticElement(curElem);
                            curAElem.From      = FromNode;
                            curAElem.To        = ToNode;

                            curAElem.Type = ElemType.Pipe;

                            curSequence.Sequence.Add(curAElem);

                            //Logic to return correct node to next element
                            if (From.GetMEPConnectorInfo().IsPrimary)
                            {
                                secNode = ToNode;
                            }
                            else if (From.GetMEPConnectorInfo().IsSecondary)
                            {
                                primNode = ToNode;
                            }
                            else
                            {
                                primNode = ToNode;
                            }

                            //Third Analytic Element
                            if (From.GetMEPConnectorInfo().IsPrimary)
                            {
                                To = cons.Tertiary;
                            }
                            else if (From.GetMEPConnectorInfo().IsSecondary)
                            {
                                To = cons.Tertiary;
                            }
                            else
                            {
                                To = cons.Secondary;
                            }

                            ToNode = new Node();
                            Model.AllNodes.Add(ToNode);
                            ToNode.PreviousCon = To;
                            curAElem           = new AnalyticElement(curElem);
                            curAElem.From      = FromNode;
                            curAElem.To        = ToNode;

                            curAElem.Type = ElemType.Pipe;

                            curSequence.Sequence.Add(curAElem);

                            //Logic to return correct node to next element
                            if (From.GetMEPConnectorInfo().IsPrimary)
                            {
                                tertNode = ToNode;
                            }
                            else if (From.GetMEPConnectorInfo().IsSecondary)
                            {
                                tertNode = ToNode;
                            }
                            else
                            {
                                secNode = ToNode;
                            }

                            //Continuation logic
                            Connector candidate1;
                            Connector candidate2;

                            if (From.GetMEPConnectorInfo().IsPrimary)
                            {
                                candidate1 = (from Connector c in Model.AllConnectors
                                              where c.Equalz(cons.Secondary, _1mmTol)
                                              select c).FirstOrDefault();
                                candidate2 = (from Connector c in Model.AllConnectors
                                              where c.Equalz(cons.Tertiary, _1mmTol)
                                              select c).FirstOrDefault();

                                if (candidate1 != null)
                                {
                                    To     = cons.Secondary;
                                    ToNode = secNode;
                                    if (candidate2 != null)
                                    {
                                        branchEnds.Add(candidate2);
                                    }
                                }
                                else if (candidate2 != null)
                                {
                                    To     = cons.Tertiary;
                                    ToNode = tertNode;
                                }
                            }
                            else if (From.GetMEPConnectorInfo().IsSecondary)
                            {
                                candidate1 = (from Connector c in Model.AllConnectors
                                              where c.Equalz(cons.Primary, _1mmTol)
                                              select c).FirstOrDefault();
                                candidate2 = (from Connector c in Model.AllConnectors
                                              where c.Equalz(cons.Tertiary, _1mmTol)
                                              select c).FirstOrDefault();

                                if (candidate1 != null)
                                {
                                    To     = cons.Primary;
                                    ToNode = primNode;
                                    if (candidate2 != null)
                                    {
                                        branchEnds.Add(candidate2);
                                    }
                                }
                                else if (candidate2 != null)
                                {
                                    To     = cons.Tertiary;
                                    ToNode = tertNode;
                                }
                            }
                            else
                            {
                                candidate1 = (from Connector c in Model.AllConnectors
                                              where c.Equalz(cons.Primary, _1mmTol)
                                              select c).FirstOrDefault();
                                candidate2 = (from Connector c in Model.AllConnectors
                                              where c.Equalz(cons.Secondary, _1mmTol)
                                              select c).FirstOrDefault();

                                if (candidate1 != null)
                                {
                                    To     = cons.Primary;
                                    ToNode = primNode;
                                    if (candidate2 != null)
                                    {
                                        branchEnds.Add(candidate2);
                                    }
                                }
                                else if (candidate2 != null)
                                {
                                    To     = cons.Secondary;
                                    ToNode = secNode;
                                }
                            }
                            break;

                        case PartType.Transition:
                            To = (from Connector c in MepUtils.GetALLConnectorsFromElements(curElem)
                                  where c.Id != From.Id
                                  select c).FirstOrDefault();
                            ToNode.PreviousCon = To;
                            Model.AllNodes.Add(ToNode);

                            curAElem.From = FromNode;
                            curAElem.To   = ToNode;

                            //Assign correct element type to analytic element
                            curAElem.Type = ElemType.Transition;

                            //Determine start dia and second dia
                            curAElem.AnalyzeReducer();

                            curSequence.Sequence.Add(curAElem);
                            break;

                        case PartType.Cap:
                            //Handles flanges because of the workaround PartType.Cap for flanges
                            //Real Caps are ignored for now
                            To = (from Connector c in MepUtils.GetALLConnectorsFromElements(curElem)
                                  where c.Id != From.Id
                                  select c).FirstOrDefault();
                            ToNode.PreviousCon = To;
                            Model.AllNodes.Add(ToNode);

                            curAElem.From = FromNode;
                            curAElem.To   = ToNode;

                            //Assign correct element type to analytic element
                            curAElem.Type = ElemType.Rigid;

                            curSequence.Sequence.Add(curAElem);
                            break;

                        case PartType.Union:
                            throw new NotImplementedException();

                        case PartType.SpudAdjustable:
                            throw new NotImplementedException();

                        default:
                            continue;
                        }
                        break;

                    case (int)BuiltInCategory.OST_PipeAccessory:
                        if (From.GetMEPConnectorInfo().IsPrimary)
                        {
                            To = cons.Secondary;
                        }
                        else if (From.GetMEPConnectorInfo().IsSecondary)
                        {
                            To = cons.Primary;
                        }
                        else
                        {
                            throw new Exception("Something went wrong with connectors of element " + curElem.Id.ToString());
                        }

                        ToNode.PreviousCon = To;
                        Model.AllNodes.Add(ToNode);

                        curAElem.From = FromNode;
                        curAElem.To   = ToNode;

                        //Assign correct element type to analytic element
                        curAElem.Type = ElemType.Rigid;

                        curSequence.Sequence.Add(curAElem);
                        break;

                    default:
                        continue;
                    }
                    break;

                default:
                    continue;
                }

                //Prepare to restart iteration
                Model.AllConnectors = Model.AllConnectors.ExceptWhere(c => c.Owner.Id.IntegerValue == curElem.Id.IntegerValue).ToList();

                From = (from Connector c in Model.AllConnectors
                        where c.Equalz(To, _1mmTol)
                        select c).FirstOrDefault();

                if (From != null)
                {
                    curElem = From.Owner;

                    FromNode         = ToNode;
                    FromNode.NextCon = From;

                    ToNode = new Node();

                    curAElem = new AnalyticElement(curElem);
                }
                else
                {
                    continueSequence = false;
                    openEnds         = openEnds.ExceptWhere(c => c.Equalz(To, _1mmTol)).ToList();

                    if (branchEnds.Count > 0 && To != null)
                    {
                        branchEnds = branchEnds.ExceptWhere(c => c.Equalz(To, _1mmTol)).ToList();
                    }

                    if (branchEnds.Count < 1)
                    {
                        Model.Sequences.Add(curSequence);
                    }
                }
            }

            //Reference ALL analytic elements in the collecting pool
            foreach (var sequence in Model.Sequences)
            {
                foreach (var item in sequence.Sequence)
                {
                    Model.AllAnalyticElements.Add(item);
                }
            }

            //Loop over ALL nodes and populate coordinate information
            foreach (Node n in Model.AllNodes)
            {
                n.PopulateCoordinates();
            }

            BuildingCoderUtilities.InfoMsg(Model.AllNodes.Count.ToString());
        }