Beispiel #1
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);
        }
Beispiel #2
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.");
            }
        }
 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()));
 }
Beispiel #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.");
            }
        }
Beispiel #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.");
            }
        }
Beispiel #7
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);
        }
Beispiel #8
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);
        }
Beispiel #9
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);
        }
        //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);
            }
        }
Beispiel #11
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());
        }