Example #1
0
 /// <summary>
 /// Checks if a parameter with the same name eixsts in a family
 /// </summary>
 /// <param name="famParam">FamilyParameter to check</param>
 /// <param name="familyInstance">The parameterset containing all family parameters</param>
 /// <returns></returns>
 internal static bool ParameterExist(FamilyParameter famParam, FamilyParameterSet parameters)
 {
     foreach (FamilyParameter param in parameters)
     {
         if (famParam.Definition.Name.Equals(param.Definition.Name))
         {
             return(true);
         }
     }
     return(false);
 }
Example #2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var doc = commandData.Application.ActiveUIDocument.Document;

            if (!doc.IsFamilyDocument)
            {
                TaskDialog.Show("Not a family editor", "Please go to family editor mode");
                return(Result.Cancelled);
            }
            FamilyManager      mgr = doc.FamilyManager;
            FamilyParameterSet fps = mgr.Parameters;



            TaskDialog.Show("Parameters", "There are " + fps.Size.ToString() + " parameters inside this family. Please choose which should be removed.");

            var data = fps.Cast <FamilyParameter>().ToList();

            using (prvaLista prvaForma = new prvaLista(data))
            {
                if (prvaForma.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        using (Transaction transaction = new Transaction(doc))
                        {
                            transaction.Start("Delete Multiple Parameters");
                            foreach (var item in prvaForma.SelektovanaLista)
                            {
                                mgr.RemoveParameter(item);
                            }
                            TaskDialog.Show("Parameters deleted", prvaForma.SelektovanaLista.Count().ToString() + " parameters have been deleted");
                            transaction.Commit();
                        }
                    }

                    catch (Exception)
                    {
                        using (Transaction transaction = new Transaction(doc))
                        {
                            transaction.Start("Delete Multiple Parameters Failed");
                            TaskDialog.Show("Cannot be deleted", "Built-in parameter cannot be deleted");
                            transaction.RollBack();
                        }
                    }
                }
            }

            return(Result.Succeeded);
        }
Example #3
0
        public static void get_all_paramters(List <string> full_files_name)
        {
//			foreach(DefinitionGroup myGroup in defFile.Groups)
//			{
//				SortedSet<string> tmp = new SortedSet<string>();
//				Globals.SP_with_groups.Add(myGroup.Name,tmp);
//				foreach(Definition df in myGroup.Definitions)
//				{
//					Globals.SP_with_groups[myGroup.Name].Add(df.Name);
            ////					TaskDialog.Show("Revit",df.Name);
            ////					return;
//				}
//			//	TaskDialog.Show("Revit",Globals.SP_with_groups[myGroup.Name].Count.ToString());
//
//			}
            Document doc;

            Globals.files_with_SP.Clear();

            foreach (string filename in full_files_name)
            {
                doc = CachedApp.OpenDocumentFile(filename);
                try{
                    if (doc.IsFamilyDocument)
                    {
                        SortedSet <FamilyParameter> tmp = new SortedSet <FamilyParameter>(new cmp());
                        FamilyManager      fm           = doc.FamilyManager;
                        FamilyParameterSet fmSet        = fm.Parameters;
                        Globals.files_with_SP.Add(filename, tmp);
                        foreach (FamilyParameter fp in fmSet)
                        {
                            if (fp.IsShared)
                            {
                                Globals.files_with_SP[filename].Add(fp);
                                //tmp.Add(fp.Definition.Name);
                            }

                            //fp.Definition.
                            //TaskDialog.Show("Revit",fp.Definition.Name);
                        }
                    }
                }
                catch (System.Exception ea)
                {
                    TaskDialog.Show("Revit", ea.Message.ToString());
                }
            }
        }
        internal bool ProcessFamily()
        {
            if (!Doc.IsFamilyDocument)
            {
                return(false);
            }

            FamilyManager famMgr = Doc.FamilyManager;

            FamilyTypeSet         famTypes    = famMgr.Types;
            FamilyTypeSetIterator famTypeItor = famTypes.ForwardIterator();

            famTypeItor.Reset();
            while (famTypeItor.MoveNext())
            {
                FamilyType famType = famTypeItor.Current as FamilyType;
                logMsgDbLn2("fam type", famType.Name);
            }

            FamilyParameterSet         famParas    = famMgr.Parameters;
            FamilyParameterSetIterator famParaItor = famParas.ForwardIterator();

            famParaItor.Reset();
            while (famParaItor.MoveNext())
            {
                FamilyParameter famPara = famParaItor.Current as FamilyParameter;
                logMsgDbLn2("fam para", famPara.Definition.Name
                            + "  :: " + famPara.Definition.ParameterGroup.ToString()
                            + "  :: " + famPara.Definition.ParameterType.ToString());
            }

            famMgr.AddParameter("ASI", BuiltInParameterGroup.PG_IDENTITY_DATA, ParameterType.Text, true);

//			using (SubTransaction st = new SubTransaction(_doc))
//			{
//				st.Start();
//				famMgr.AddParameter("ASI", BuiltInParameterGroup.PG_IDENTITY_DATA, ParameterType.Text, true);
//				st.Commit();
//			}

            return(true);
        }
        public Document settingParamenters(string eleName, string eleXPath, string elefName, Document Revit_Doc)
        {
            //MessageBox.Show(elefName);
            //根据名称在工程文件中查找出对应族
            FilteredElementCollector allElements  = new FilteredElementCollector(Revit_Doc);
            ElementClassFilter       familyFilter = new ElementClassFilter(typeof(Family));

            allElements = allElements.WherePasses(familyFilter);
            var filterFamilyList = from f in allElements
                                   where f.Name.ToString() == elefName
                                   select f as Family;
            //MessageBox.Show(filterFamilyList.ToList<Family>()[0].ToString());

            //allElements = new FilteredElementCollector(Revit_Doc);
            //ElementClassFilter familySymbolFilter = new ElementClassFilter(typeof(FamilySymbol));
            //allElements = allElements.WherePasses(familySymbolFilter);
            //var filterList = from f in allElements
            //                 where f.Name.ToString() == eleName && (f as FamilySymbol).Family.ToString() == elefName
            //                 select (f as FamilySymbol).Family ;
            //Family filtedFamily = filterList.ToList<Family>().FirstOrDefault();
            ////if (filterList != null)
            ////{ MessageBox.Show(filterList.ToList<Family>()[0].ToString()); }

            Family filtedFamily = filterFamilyList.ToList <Family>().FirstOrDefault();;

            MessageBox.Show(filtedFamily.Name.ToString());
            //---------------------------------------------------
            //MessageBox.Show(eleName);
            //if (filtedFamily == null)
            //{ MessageBox.Show("filtedFamily is null!!"); }
            //---------------------------------------------------
            //
            Document familyDoc = Revit_Doc.EditFamily(filtedFamily);

            if (null != familyDoc && familyDoc.IsFamilyDocument == true)
            {
                DataTable xdte = new DataTable();
                //读取xls文件
                ExcelHelper ExcelHelper = new ExcelHelper();
                DataTable   xdt         = ExcelHelper.Reading_Excel_Information(eleXPath);
                //获取参数集
                FamilyParameterSet rfadocParas         = familyDoc.FamilyManager.Parameters;
                List <string>      rfadocParasListName = new List <string>();
                foreach (FamilyParameter rfadocPara in rfadocParas)
                {
                    rfadocParasListName.Add(rfadocPara.Definition.Name);
                }

                FamilyManager familyMgr = familyDoc.FamilyManager;

                if (clearsymbol == true)
                {
                    //清空族内所有类型 仅保留默认族类型
                    int typesizes = familyMgr.Types.Size;
                    if (familyMgr.Types.Size > 1 && familyMgr.Types.Size != 0)
                    {
                        for (int typenumber = 0; typenumber < typesizes - 1; typenumber++)
                        {
                            if (familyMgr.CurrentType != null)
                            {
                                Transaction DeleteType = new Transaction(familyDoc, "DeleteType");
                                DeleteType.Start();
                                familyMgr.DeleteCurrentType();
                                DeleteType.Commit();
                            }
                        }
                    }
                }

                if (clearpara == true)
                {
                    //清空族内所有参数条目
                    foreach (FamilyParameter fp in familyMgr.Parameters)
                    {
                        if (fp.Definition.ParameterGroup == BuiltInParameterGroup.PG_ELECTRICAL)
                        {
                            Transaction RemoveParameter = new Transaction(familyDoc, "RemoveParameter");
                            RemoveParameter.Start();
                            familyMgr.RemoveParameter(fp);
                            RemoveParameter.Commit();
                        }
                    }
                }
                //开始添加

                Transaction addParameter = new Transaction(familyDoc, "AddParameters");
                addParameter.Start();

                string paraname = null;
                BuiltInParameterGroup paragroup = BuiltInParameterGroup.PG_ELECTRICAL;;
                ParameterType         paraType  = ParameterType.Text;;
                bool isInstance = false;

                string        paravalue         = null;
                List <string> distinctparanames = new List <string>();

                //判断xls表中与原有rfa文件内重复的条目  放入distinctparanames列表
                for (int i = 0; i < xdt.Rows.Count; i++)
                {
                    foreach (FamilyParameter fp in familyMgr.Parameters)
                    {
                        if (fp.Definition.Name == xdt.Rows[i]["paraname"].ToString())
                        {
                            distinctparanames.Add(fp.Definition.Name);
                            MessageBox.Show(fp.Definition.Name);
                        }
                    }
                }
                //遍历xls添加属性条目
                for (int i = 0; i < xdt.Rows.Count; i++)
                {
                    //获取表中条目名称判断是否重复 重复则继续下一次循环
                    paraname = xdt.Rows[i]["paraname"].ToString();

                    foreach (string disstr in distinctparanames)
                    {
                        if (disstr == paraname)
                        {
                            continue;
                        }
                    }

                    //通过的条目名称
                    if (xdt.Rows[i]["paragroup"] == null)
                    {
                        paragroup = BuiltInParameterGroup.PG_ELECTRICAL;
                    }
                    else
                    {
                        #region  参数分组对照  用于RevitAPI2016A
                        switch (xdt.Rows[i]["paragroup"].ToString())
                        {
                        case "PG_RELEASES_MEMBER_FORCES": paragroup = BuiltInParameterGroup.PG_RELEASES_MEMBER_FORCES; break;

                        case "PG_SECONDARY_END": paragroup = BuiltInParameterGroup.PG_SECONDARY_END; break;

                        case "PG_PRIMARY_END": paragroup = BuiltInParameterGroup.PG_PRIMARY_END; break;

                        case "PG_MOMENTS": paragroup = BuiltInParameterGroup.PG_MOMENTS; break;

                        case "PG_FORCES": paragroup = BuiltInParameterGroup.PG_FORCES; break;

                        case "PG_FABRICATION_PRODUCT_DATA": paragroup = BuiltInParameterGroup.PG_GEOMETRY_POSITIONING; break;

                        case "PG_REFERENCE": paragroup = BuiltInParameterGroup.PG_REFERENCE; break;

                        case "PG_GEOMETRY_POSITIONING": paragroup = BuiltInParameterGroup.PG_GEOMETRY_POSITIONING; break;

                        case "PG_DIVISION_GEOMETRY": paragroup = BuiltInParameterGroup.PG_DIVISION_GEOMETRY; break;

                        case "PG_SEGMENTS_FITTINGS": paragroup = BuiltInParameterGroup.PG_SEGMENTS_FITTINGS; break;

                        case "PG_CONTINUOUSRAIL_END_TOP_EXTENSION": paragroup = BuiltInParameterGroup.PG_CONTINUOUSRAIL_END_TOP_EXTENSION; break;

                        case "PG_CONTINUOUSRAIL_BEGIN_BOTTOM_EXTENSION": paragroup = BuiltInParameterGroup.PG_CONTINUOUSRAIL_BEGIN_BOTTOM_EXTENSION; break;

                        case "PG_STAIRS_WINDERS": paragroup = BuiltInParameterGroup.PG_STAIRS_WINDERS; break;

                        case "PG_STAIRS_SUPPORTS": paragroup = BuiltInParameterGroup.PG_STAIRS_SUPPORTS; break;

                        case "PG_STAIRS_OPEN_END_CONNECTION": paragroup = BuiltInParameterGroup.PG_STAIRS_OPEN_END_CONNECTION; break;

                        case "PG_RAILING_SYSTEM_SECONDARY_FAMILY_HANDRAILS": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SECONDARY_FAMILY_HANDRAILS; break;

                        case "PG_TERMINTATION": paragroup = BuiltInParameterGroup.PG_TERMINTATION; break;

                        case "PG_STAIRS_TREADS_RISERS": paragroup = BuiltInParameterGroup.PG_STAIRS_TREADS_RISERS; break;

                        case "PG_STAIRS_CALCULATOR_RULES": paragroup = BuiltInParameterGroup.PG_STAIRS_CALCULATOR_RULES; break;

                        case "PG_SPLIT_PROFILE_DIMENSIONS": paragroup = BuiltInParameterGroup.PG_SPLIT_PROFILE_DIMENSIONS; break;

                        case "PG_LENGTH": paragroup = BuiltInParameterGroup.PG_LENGTH; break;

                        case "PG_NODES": paragroup = BuiltInParameterGroup.PG_NODES; break;

                        case "PG_ANALYTICAL_PROPERTIES": paragroup = BuiltInParameterGroup.PG_ANALYTICAL_PROPERTIES; break;

                        case "PG_ANALYTICAL_ALIGNMENT": paragroup = BuiltInParameterGroup.PG_ANALYTICAL_ALIGNMENT; break;

                        case "PG_SYSTEMTYPE_RISEDROP": paragroup = BuiltInParameterGroup.PG_SYSTEMTYPE_RISEDROP; break;

                        case "PG_LINING": paragroup = BuiltInParameterGroup.PG_LINING; break;

                        case "PG_INSULATION": paragroup = BuiltInParameterGroup.PG_INSULATION; break;

                        case "PG_OVERALL_LEGEND": paragroup = BuiltInParameterGroup.PG_OVERALL_LEGEND; break;

                        case "PG_VISIBILITY": paragroup = BuiltInParameterGroup.PG_VISIBILITY; break;

                        case "PG_SUPPORT": paragroup = BuiltInParameterGroup.PG_SUPPORT; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_V_GRID": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_V_GRID; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_U_GRID": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_U_GRID; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_POSTS": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_POSTS; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_PATTERN_REMAINDER": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_PATTERN_REMAINDER; break;

                        case "PG_RAILING_SYSTEM_SEGMENT_PATTERN_REPEAT": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_SEGMENT_PATTERN_REPEAT; break;

                        case "PG_RAILING_SYSTEM_FAMILY_SEGMENT_PATTERN": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_FAMILY_SEGMENT_PATTERN; break;

                        case "PG_RAILING_SYSTEM_FAMILY_HANDRAILS": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_FAMILY_HANDRAILS; break;

                        case "PG_RAILING_SYSTEM_FAMILY_TOP_RAIL": paragroup = BuiltInParameterGroup.PG_RAILING_SYSTEM_FAMILY_TOP_RAIL; break;

                        case "PG_CONCEPTUAL_ENERGY_DATA_BUILDING_SERVICES": paragroup = BuiltInParameterGroup.PG_CONCEPTUAL_ENERGY_DATA_BUILDING_SERVICES; break;

                        case "PG_DATA": paragroup = BuiltInParameterGroup.PG_DATA; break;

                        case "PG_ELECTRICAL_CIRCUITING": paragroup = BuiltInParameterGroup.PG_ELECTRICAL_CIRCUITING; break;

                        case "PG_GENERAL": paragroup = BuiltInParameterGroup.PG_GENERAL; break;

                        case "PG_FLEXIBLE": paragroup = BuiltInParameterGroup.PG_FLEXIBLE; break;

                        case "PG_ENERGY_ANALYSIS_CONCEPTUAL_MODEL": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS_CONCEPTUAL_MODEL; break;

                        case "PG_ENERGY_ANALYSIS_DETAILED_MODEL": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS_DETAILED_MODEL; break;

                        case "PG_ENERGY_ANALYSIS_DETAILED_AND_CONCEPTUAL_MODELS": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS_DETAILED_AND_CONCEPTUAL_MODELS; break;

                        case "PG_FITTING": paragroup = BuiltInParameterGroup.PG_FITTING; break;

                        case "PG_CONCEPTUAL_ENERGY_DATA": paragroup = BuiltInParameterGroup.PG_CONCEPTUAL_ENERGY_DATA; break;

                        case "PG_AREA": paragroup = BuiltInParameterGroup.PG_AREA; break;

                        case "PG_ADSK_MODEL_PROPERTIES": paragroup = BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES; break;

                        case "PG_CURTAIN_GRID_V": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_V; break;

                        case "PG_CURTAIN_GRID_U": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_U; break;

                        case "PG_DISPLAY": paragroup = BuiltInParameterGroup.PG_DISPLAY; break;

                        case "PG_ANALYSIS_RESULTS": paragroup = BuiltInParameterGroup.PG_ANALYSIS_RESULTS; break;

                        case "PG_SLAB_SHAPE_EDIT": paragroup = BuiltInParameterGroup.PG_SLAB_SHAPE_EDIT; break;

                        case "PG_LIGHT_PHOTOMETRICS": paragroup = BuiltInParameterGroup.PG_LIGHT_PHOTOMETRICS; break;

                        case "PG_PATTERN_APPLICATION": paragroup = BuiltInParameterGroup.PG_PATTERN_APPLICATION; break;

                        case "PG_GREEN_BUILDING": paragroup = BuiltInParameterGroup.PG_GREEN_BUILDING; break;

                        case "PG_PROFILE_2": paragroup = BuiltInParameterGroup.PG_PROFILE_2; break;

                        case "PG_PROFILE_1": paragroup = BuiltInParameterGroup.PG_PROFILE_1; break;

                        case "PG_PROFILE": paragroup = BuiltInParameterGroup.PG_PROFILE; break;

                        case "PG_TRUSS_FAMILY_BOTTOM_CHORD": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_BOTTOM_CHORD; break;

                        case "PG_TRUSS_FAMILY_TOP_CHORD": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_TOP_CHORD; break;

                        case "PG_TRUSS_FAMILY_DIAG_WEB": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_DIAG_WEB; break;

                        case "PG_TRUSS_FAMILY_VERT_WEB": paragroup = BuiltInParameterGroup.PG_TRUSS_FAMILY_VERT_WEB; break;

                        case "PG_TITLE": paragroup = BuiltInParameterGroup.PG_TITLE; break;

                        case "PG_FIRE_PROTECTION": paragroup = BuiltInParameterGroup.PG_FIRE_PROTECTION; break;

                        case "PG_ROTATION_ABOUT": paragroup = BuiltInParameterGroup.PG_ROTATION_ABOUT; break;

                        case "PG_TRANSLATION_IN": paragroup = BuiltInParameterGroup.PG_TRANSLATION_IN; break;

                        case "PG_ANALYTICAL_MODEL": paragroup = BuiltInParameterGroup.PG_ANALYTICAL_MODEL; break;

                        case "PG_REBAR_ARRAY": paragroup = BuiltInParameterGroup.PG_REBAR_ARRAY; break;

                        case "PG_REBAR_SYSTEM_LAYERS": paragroup = BuiltInParameterGroup.PG_REBAR_SYSTEM_LAYERS; break;

                        case "PG_CURTAIN_GRID": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID; break;

                        case "PG_CURTAIN_MULLION_2": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_2; break;

                        case "PG_CURTAIN_MULLION_HORIZ": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_HORIZ; break;

                        case "PG_CURTAIN_MULLION_1": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_1; break;

                        case "PG_CURTAIN_MULLION_VERT": paragroup = BuiltInParameterGroup.PG_CURTAIN_MULLION_VERT; break;

                        case "PG_CURTAIN_GRID_2": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_2; break;

                        case "PG_CURTAIN_GRID_HORIZ": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_HORIZ; break;

                        case "PG_CURTAIN_GRID_1": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_1; break;

                        case "PG_CURTAIN_GRID_VERT": paragroup = BuiltInParameterGroup.PG_CURTAIN_GRID_VERT; break;

                        case "PG_IFC": paragroup = BuiltInParameterGroup.PG_IFC; break;

                        case "PG_AELECTRICAL": paragroup = BuiltInParameterGroup.PG_AELECTRICAL; break;

                        case "PG_ENERGY_ANALYSIS": paragroup = BuiltInParameterGroup.PG_ENERGY_ANALYSIS; break;

                        case "PG_STRUCTURAL_ANALYSIS": paragroup = BuiltInParameterGroup.PG_STRUCTURAL_ANALYSIS; break;

                        case "PG_MECHANICAL_AIRFLOW": paragroup = BuiltInParameterGroup.PG_MECHANICAL_AIRFLOW; break;

                        case "PG_MECHANICAL_LOADS": paragroup = BuiltInParameterGroup.PG_MECHANICAL_LOADS; break;

                        case "PG_ELECTRICAL_LOADS": paragroup = BuiltInParameterGroup.PG_ELECTRICAL_LOADS; break;

                        case "PG_ELECTRICAL_LIGHTING": paragroup = BuiltInParameterGroup.PG_ELECTRICAL_LIGHTING; break;

                        case "PG_TEXT": paragroup = BuiltInParameterGroup.PG_TEXT; break;

                        case "PG_VIEW_CAMERA": paragroup = BuiltInParameterGroup.PG_VIEW_CAMERA; break;

                        case "PG_VIEW_EXTENTS": paragroup = BuiltInParameterGroup.PG_VIEW_EXTENTS; break;

                        case "PG_PATTERN": paragroup = BuiltInParameterGroup.PG_PATTERN; break;

                        case "PG_CONSTRAINTS": paragroup = BuiltInParameterGroup.PG_CONSTRAINTS; break;

                        case "PG_PHASING": paragroup = BuiltInParameterGroup.PG_PHASING; break;

                        case "PG_MECHANICAL": paragroup = BuiltInParameterGroup.PG_MECHANICAL; break;

                        case "PG_STRUCTURAL": paragroup = BuiltInParameterGroup.PG_STRUCTURAL; break;

                        case "PG_PLUMBING": paragroup = BuiltInParameterGroup.PG_PLUMBING; break;

                        case "PG_ELECTRICAL": paragroup = BuiltInParameterGroup.PG_ELECTRICAL; break;

                        case "PG_STAIR_STRINGERS": paragroup = BuiltInParameterGroup.PG_STAIR_STRINGERS; break;

                        case "PG_STAIR_RISERS": paragroup = BuiltInParameterGroup.PG_STAIR_RISERS; break;

                        case "PG_STAIR_TREADS": paragroup = BuiltInParameterGroup.PG_STAIR_TREADS; break;

                        case "PG_MATERIALS": paragroup = BuiltInParameterGroup.PG_MATERIALS; break;

                        case "PG_GRAPHICS": paragroup = BuiltInParameterGroup.PG_GRAPHICS; break;

                        case "PG_CONSTRUCTION": paragroup = BuiltInParameterGroup.PG_CONSTRUCTION; break;

                        case "PG_GEOMETRY": paragroup = BuiltInParameterGroup.PG_GEOMETRY; break;

                        case "PG_IDENTITY_DATA": paragroup = BuiltInParameterGroup.PG_IDENTITY_DATA; break;

                        case "INVALID": paragroup = BuiltInParameterGroup.INVALID; break;
                        }
                        #endregion
                    }
                    if (xdt.Rows[i]["paratype"] == null)
                    {
                        paraType = ParameterType.Text;
                    }
                    else
                    {
                        #region 参数类型对照 用于RevitAPI2016
                        switch (xdt.Rows[i]["paratype"].ToString())
                        {
                        case "Text": paraType = ParameterType.Text; break;

                            //case "Invalid": paraType = ParameterType.Invalid; break;
                            //case "Integer": paraType = ParameterType.Integer; break;

                            //case "Number": paraType = ParameterType.Number; break;
                            //case "Length": paraType = ParameterType.Length; break;
                            //case "Volume": paraType = ParameterType.Volume; break;
                            //case "Area": paraType = ParameterType.Area; break;
                            //case "Angle": paraType = ParameterType.Angle; break;
                            //case "URL": paraType = ParameterType.URL; break;
                            //case "Material": paraType = ParameterType.Material; break;
                            //case "YesNo": paraType = ParameterType.YesNo; break;
                            //case "Force": paraType = ParameterType.Force; break;
                            //case "NumberOfPoles": paraType = ParameterType.NumberOfPoles; break;
                            //case "AreaForce": paraType = ParameterType.AreaForce; break;
                            //case "Moment": paraType = ParameterType.Moment; break;
                            //case "FixtureUnit": paraType = ParameterType.FixtureUnit; break;
                            //case "FamilyType": paraType = ParameterType.FamilyType; break;
                            //case "LoadClassification": paraType = ParameterType.LoadClassification; break;
                            //case "Image": paraType = ParameterType.Image; break;
                            //case "HVACDensity": paraType = ParameterType.HVACDensity; break;
                            //case "HVACEnergy": paraType = ParameterType.HVACEnergy; break;
                            //case "HVACFriction": paraType = ParameterType.HVACFriction; break;
                            //case "HVACPower": paraType = ParameterType.HVACPower; break;
                            //case "HVACPowerDensity": paraType = ParameterType.HVACPowerDensity; break;
                            //case "HVACPressure": paraType = ParameterType.HVACPressure; break;
                            //case "HVACTemperature": paraType = ParameterType.HVACTemperature; break;
                            //case "HVACVelocity": paraType = ParameterType.HVACVelocity; break;
                            //case "HVACAirflow": paraType = ParameterType.HVACAirflow; break;
                            //case "HVACDuctSize": paraType = ParameterType.HVACDuctSize; break;
                            //case "HVACCrossSection": paraType = ParameterType.HVACCrossSection; break;
                            //case "HVACHeatGain": paraType = ParameterType.HVACHeatGain; break;
                            //case "ElectricalCurrent": paraType = ParameterType.ElectricalCurrent; break;
                            //case "ElectricalPotential": paraType = ParameterType.ElectricalPotential; break;
                            //case "ElectricalFrequency": paraType = ParameterType.ElectricalFrequency; break;
                            //case "ElectricalIlluminance": paraType = ParameterType.ElectricalIlluminance; break;
                            //case "ElectricalLuminousFlux": paraType = ParameterType.ElectricalLuminousFlux; break;
                            //case "ElectricalPower": paraType = ParameterType.ElectricalPower; break;
                            //case "HVACRoughness": paraType = ParameterType.HVACRoughness; break;
                            //case "ElectricalApparentPower": paraType = ParameterType.ElectricalApparentPower; break;
                            //case "ElectricalPowerDensity": paraType = ParameterType.ElectricalPowerDensity; break;
                            //case "PipingDensity": paraType = ParameterType.PipingDensity; break;
                            //case "PipingFlow": paraType = ParameterType.PipingFlow; break;
                            //case "PipingFriction": paraType = ParameterType.PipingFriction; break;
                            //case "PipingPressure": paraType = ParameterType.PipingPressure; break;
                            //case "PipingTemperature": paraType = ParameterType.PipingTemperature; break;
                            //case "PipingVelocity": paraType = ParameterType.PipingVelocity; break;
                            //case "PipingViscosity": paraType = ParameterType.PipingViscosity; break;
                            //case "PipeSize": paraType = ParameterType.PipeSize; break;
                            //case "PipingRoughness": paraType = ParameterType.PipingRoughness; break;
                            //case "Stress": paraType = ParameterType.Stress; break;
                            //case "UnitWeight": paraType = ParameterType.UnitWeight; break;
                            //case "ThermalExpansion": paraType = ParameterType.ThermalExpansion; break;
                            //case "LinearMoment": paraType = ParameterType.LinearMoment; break;
                            //case "ForcePerLength": paraType = ParameterType.ForcePerLength; break;
                            //case "ForceLengthPerAngle": paraType = ParameterType.ForceLengthPerAngle; break;
                            //case "LinearForcePerLength": paraType = ParameterType.LinearForcePerLength; break;
                            //case "LinearForceLengthPerAngle": paraType = ParameterType.LinearForceLengthPerAngle; break;
                            //case "AreaForcePerLength": paraType = ParameterType.AreaForcePerLength; break;
                            //case "PipingVolume": paraType = ParameterType.PipingVolume; break;
                            //case "HVACViscosity": paraType = ParameterType.HVACViscosity; break;
                            //case "HVACCoefficientOfHeatTransfer": paraType = ParameterType.HVACCoefficientOfHeatTransfer; break;
                            //case "HVACAirflowDensity": paraType = ParameterType.HVACAirflowDensity; break;
                            //case "Slope": paraType = ParameterType.Slope; break;
                            //case "HVACCoolingLoad": paraType = ParameterType.HVACCoolingLoad; break;
                            //case "HVACCoolingLoadDividedByArea": paraType = ParameterType.HVACCoolingLoadDividedByArea; break;
                            //case "HVACCoolingLoadDividedByVolume": paraType = ParameterType.HVACCoolingLoadDividedByVolume; break;
                            //case "HVACHeatingLoad": paraType = ParameterType.HVACHeatingLoad; break;
                            //case "HVACHeatingLoadDividedByArea": paraType = ParameterType.HVACHeatingLoadDividedByArea; break;
                            //case "Weight": paraType = ParameterType.Weight; break;
                        }
                        #endregion
                    }
                    if (xdt.Rows[i]["paratag"].ToString() == "是")
                    {
                        isInstance = true;
                    }
                    else if (xdt.Rows[i]["paratag"].ToString() == "否")
                    {
                        isInstance = false;
                    }
                    if (xdt.Rows[i]["paravalue"].ToString() == null)
                    {
                        paravalue = "NA";
                    }
                    else
                    {
                        paravalue = xdt.Rows[i]["paravalue"].ToString();
                    }

                    //bool checkDistinct = false;
                    //foreach (FamilyParameter fp in familyMgr.Parameters)
                    //{
                    //    if (fp.Definition.Name == xdt.Rows[i]["paraname"].ToString())
                    //    {
                    //        checkDistinct = true;
                    //    }
                    //}
                    //if (checkDistinct == true)
                    //{
                    //    continue;
                    //}
                    //else
                    //{
                    try
                    {
                        FamilyParameter newParameter = familyMgr.AddParameter(paraname, paragroup, paraType, isInstance);
                    }
                    catch (Exception efec)
                    {
                        MessageBox.Show(efec.ToString());
                        continue;
                    }
                    //创建族参数(每个参数两秒)
                    //familyMgr.Set(newParameter, paravalue);
                    //}
                }

                try
                {
                    for (int i = 0; i < xdt.Rows.Count; i++)
                    {
                        paraname = xdt.Rows[i]["paraname"].ToString();
                        foreach (FamilyParameter fp in familyMgr.Parameters)
                        {
                            StorageType fst = fp.StorageType;
                            if (fp.Definition.Name == xdt.Rows[i]["paraname"].ToString())
                            {
                                if (xdt.Rows[i]["paravalue"].ToString() == null && fst.ToString() == "String")
                                {
                                    paravalue = "NA";
                                    familyMgr.Set(fp, paravalue);
                                }
                                else
                                {
                                    //paravalue = xdt.Rows[i]["paravalue"].ToString();
                                    #region
                                    switch (fst.ToString())
                                    {
                                    case "Integer": int paravint = Convert.ToInt32(xdt.Rows[i]["paravalue"].ToString()); familyMgr.Set(fp, paravint);; break;

                                    case "Double": double paravdouble = Convert.ToDouble(xdt.Rows[i]["paravalue"].ToString()); familyMgr.Set(fp, paravdouble); break;

                                    case "String": string paravstring = xdt.Rows[i]["paravalue"].ToString(); familyMgr.Set(fp, paravstring); break;

                                    case "ElementId": ElementId paravid = new ElementId(Convert.ToInt32(xdt.Rows[i]["paravalue"].ToString())); familyMgr.Set(fp, paravid); break;

                                    case "None":   break;
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                }
                catch (Exception eeef)
                { /*MessageBox.Show(eeef.ToString());*/ }

                SaveOptions opt = new SaveOptions();
                addParameter.Commit();
            }

            return(familyDoc);
        }
        public void settingFamilyParamentersValue(Document doc, string familyFilePath, string parameterFilePath)
        {
            //读取xls文件
            ExcelHelper ExcelHelper = new ExcelHelper();
            DataTable   dt          = ExcelHelper.Reading_Excel_Information(parameterFilePath);

            //获取参数集
            FamilyParameterSet rfadocParas         = doc.FamilyManager.Parameters;
            List <string>      rfadocParasListName = new List <string>();

            foreach (FamilyParameter rfadocPara in rfadocParas)
            {
                rfadocParasListName.Add(rfadocPara.Definition.Name);
            }

            #region
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                List <string> ls_ParameterNames = new List <string>();
                //ls_ParameterNames.Add(dt.Rows[i][0].ToString);
            }
            #endregion

            #region 族参数操作1
            FamilyManager familyMgr = doc.FamilyManager;

            //清空族内所有类型 仅保留默认族类型
            int typesizes = familyMgr.Types.Size;
            if (familyMgr.Types.Size > 1 && familyMgr.Types.Size != 0)
            {
                for (int typenumber = 0; typenumber < typesizes - 1; typenumber++)
                {
                    if (familyMgr.CurrentType != null)
                    {
                        Transaction DeleteType = new Transaction(doc, "DeleteType");
                        DeleteType.Start();
                        familyMgr.DeleteCurrentType();
                        DeleteType.Commit();
                    }
                }
            }

            //清空族内所有参数条目
            foreach (FamilyParameter fp in familyMgr.Parameters)
            {
                if (fp.Definition.ParameterGroup == BuiltInParameterGroup.PG_ELECTRICAL)
                {
                    Transaction RemoveParameter = new Transaction(doc, "RemoveParameter");
                    RemoveParameter.Start();
                    familyMgr.RemoveParameter(fp);
                    RemoveParameter.Commit();
                }
            }

            //开始添加

            Transaction addParameter = new Transaction(doc, "AddParameters");
            addParameter.Start();

            List <string> paraNames   = new List <string>();
            List <bool>   isInstances = new List <bool>();
            List <string> paravalues  = new List <string>();
            //设置族参数的类别和类型
            BuiltInParameterGroup paraGroup   = BuiltInParameterGroup.PG_ELECTRICAL;
            BuiltInParameterGroup paraGroupEx = BuiltInParameterGroup.PG_GENERAL;
            ParameterType         paraType    = ParameterType.Text;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string paraName = dt.Rows[i]["paraname"].ToString();
                paraNames.Add(paraName);

                //设置族参数为实例参数
                bool isInstance = true;
                if (dt.Rows[i]["paratag"].ToString() == "是")
                {
                    isInstance = true;
                }
                else
                {
                    isInstance = false;
                }
                isInstances.Add(isInstance);

                paravalues.Add(dt.Rows[i]["paravalue"].ToString());
            }

            for (int k = 0; k < paraNames.Count(); k++)
            {
                int tag = 0;
                if (paraNames[k].Contains("M_") || paraNames[k].Contains("D_") || paraNames[k].Contains("设计-") || paraNames[k].Contains("管理-"))
                {
                    FamilyParameter newParameter = familyMgr.AddParameter(paraNames[k], paraGroup, paraType, isInstances[k]);
                    //创建族参数(每个参数两秒)
                    familyMgr.Set(newParameter, paravalues[k]);
                }
                else
                {
                    foreach (var fpln in rfadocParasListName)
                    {
                        if (paraNames[k] == fpln)
                        {
                            tag = 1;
                        }
                    }
                    if (tag == 1)
                    {
                        continue;
                    }
                    else
                    {
                        FamilyParameter newParameter = familyMgr.AddParameter(paraNames[k], paraGroupEx, paraType, isInstances[k]);
                    }
                }
            }
            SaveOptions opt = new SaveOptions();
            //doc.Save(opt);
            //doc.SaveAs(@"D:\"+);
            //doc.Close();
            addParameter.Commit();
            #endregion
        }
Example #7
0
        //Here, the families or types will be made
        private static void CreateFamilyTypesFromTable(UIApplication uiApp, MainUI uiForm, string saveDirectory, DataGridView dgv, SaveAsOptions saveAsOptions, string familyFileToUse)
        {
            //First thing to do is open the family document and access the FamilyManager
            RVTDocument   famDoc = RVTOperations.OpenRevitFile(uiApp, familyFileToUse);
            FamilyManager famMan = famDoc.FamilyManager;

            string tempFamilyPath = "";

            //Next, delete all of the family types except one from the family and save the file off for temporary use
            try
            {
                //This is in a Try/Catch becuse there is a possibility for failure
                RVTOperations.DeleteFamilyTypes(famDoc, famMan);
                tempFamilyPath = saveDirectory + "\\" + String.Format(famDoc.Title).Replace(".rfa", "") + "_temp.rfa";
                famDoc.SaveAs(tempFamilyPath, saveAsOptions);
            }
            catch { MessageBox.Show("Could not save out a temporary family file to the location where the families are to be saved. Verify the location is not read-only."); }
            //Ensure the open family gets closed
            finally { famDoc.Close(); }

            //Then, reopen the temporary family if it exists
            if (tempFamilyPath != "")
            {
                //Get all of the parameters in the family and add them to a dictionary indexed by the parameter name
                RVTDocument        newFamDoc  = RVTOperations.OpenRevitFile(uiApp, tempFamilyPath);
                FamilyManager      newFamMan  = newFamDoc.FamilyManager;
                FamilyParameterSet parameters = newFamMan.Parameters;
                Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                foreach (FamilyParameter param in parameters)
                {
                    famParamDict.Add(param.Definition.Name, param);
                }

                //These integer values will be used to increment loops
                int rowsCount    = dgv.Rows.Count;
                int columnsCount = dgv.Columns.Count;

                //Keep track of what family types were made so the script can later delete out the one that pre-existed in the family but is not needed.
                List <string> familyTypesMade = new List <string>();
                //If the user decide to make types per row instead of families per row...
                if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "Combine Types (1 File)")
                {
                    //The progress bar should be prepared using the number of rows multipled by the number of columns for the number of steps to perform. This gives a better indication of progress than doing it based on the number of rows
                    uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0;
                    uiForm.multiCatCFFEFamiliesProgressBar.Maximum = (rowsCount - 1) * (columnsCount - 1);
                    uiForm.multiCatCFFEFamiliesProgressBar.Step    = 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Visible = true;

                    //Open the transaction
                    Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes");
                    t2.Start();
                    //The maximum of rows is greater than the maximum index value by 1, so this uses < to stop before an index out of range exception occurs. Also, the index starts at 1 instead of 0 because the top row is the info about the data type
                    for (int i = 1; i < rowsCount; i++)
                    {
                        //The type name is in the first column.
                        string newTypeName = dgv.Rows[i].Cells[0].Value.ToString();
                        //This operation will get the existing type names in the family as new ones are added to avoide duplication
                        Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(newFamMan);
                        //If the type does not exist in the dictionary...
                        if (!existingTypeNames.Keys.Contains(newTypeName))
                        {
                            //Create a new type and add it to the list of types made
                            FamilyType newType = newFamMan.NewType(newTypeName);
                            newFamMan.CurrentType = newType;
                            familyTypesMade.Add(newType.Name);
                        }
                        else
                        {
                            //Otherwise set the current type in the family manager to the pre-existing one with the name of the one to be created
                            newFamMan.CurrentType = existingTypeNames[newTypeName];
                            //Add that one to the list of types made, though it wasn't actually made
                            familyTypesMade.Add(newFamMan.CurrentType.Name);
                        }

                        //Next, cycle through the columns, again starting with the column at index 1 and incrementing the columns to one less than the number of columns
                        for (int j = 1; j < columnsCount; j++)
                        {
                            //Get the parameter name from the first column's header text
                            string paramName = dgv.Columns[j].HeaderText;
                            //Get the storage type from the first row
                            string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString();
                            var    paramValue             = dgv.Rows[i].Cells[j].Value;
                            //Assuming the parameter value is set...
                            if (paramValue.ToString() != "")
                            {
                                //Set the parameter given the information about the FamilyManager, parameter definition, parameter type, parameter data type, value to set, and whether or not to convert inches to feet. Because this script relies on inch input, this needs done to convert to feet used by the Revit API
                                FamilyParameter param     = famParamDict[paramName];
                                ParameterType   paramType = param.Definition.ParameterType;
                                RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true);
                            }
                            //Step forward the progress bar for this parameter
                            uiForm.multiCatCFFEFamiliesProgressBar.PerformStep();
                        }
                    }
                    t2.Commit();

                    //In another transaction, delete the pre-existing type used to generate the other types
                    Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes");
                    t3.Start();
                    foreach (FamilyType type in newFamMan.Types)
                    {
                        //Set the current type to the one with the pre-existing type name and delete it
                        if (!familyTypesMade.Contains(type.Name))
                        {
                            newFamMan.CurrentType = type;
                            newFamMan.DeleteCurrentType();
                        }
                    }
                    t3.Commit();

                    //Save out the family to the directory and remove the _temp from the name
                    newFamDoc.SaveAs(saveDirectory + "\\" + String.Format(newFamDoc.Title).Replace("_temp", "") + ".rfa", saveAsOptions);
                    newFamDoc.Close();
                }

                //If the user chose to make a family file per row, the family will be saved out multiple times
                else if (uiForm.multiCatCFFEFamilyCreationComboBox.SelectedItem.ToString() == "1 Family Per Type (Multiple Files)")
                {
                    //Set the number of steps for the progress bar to the number of rows with families to make
                    uiForm.multiCatCFFEFamiliesProgressBar.Minimum = 0;
                    uiForm.multiCatCFFEFamiliesProgressBar.Maximum = rowsCount - 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Step    = 1;
                    uiForm.multiCatCFFEFamiliesProgressBar.Visible = true;

                    //Again, starting at row index 1 because the first is the information about the data types. This loop will produce a family per row. One familly will be opened and saved off multiple times, performing the process of deleting types, adding a default type, and setting parameters before each save
                    for (int i = 1; i < rowsCount; i++)
                    {
                        Transaction t2 = new Transaction(newFamDoc, "MakeNewTypes");
                        t2.Start();
                        //Create a new type using the name of the type in the first column
                        FamilyType newType = newFamMan.NewType(dgv.Rows[i].Cells[0].Value.ToString());
                        //Clean up the family file name by leaving everything that does not pass the regular expression in CleanFileName

                        string saveName = GeneralOperations.CleanFileName(newType.Name);
                        if (saveName != "")
                        {
                            //Assuming nothing went wrong modifying the family name...
                            newFamMan.CurrentType = newType;
                            //Cycle through the columns to set the parameter values this performs the same operations as those above for making 1 family with multiple types
                            for (int j = 1; j < columnsCount; j++)
                            {
                                string paramName = dgv.Columns[j].HeaderText;
                                string paramStorageTypeString = dgv.Rows[0].Cells[j].Value.ToString();
                                var    paramValue             = dgv.Rows[i].Cells[j].Value;
                                if (paramValue.ToString() != "")
                                {
                                    FamilyParameter param     = famParamDict[paramName];
                                    ParameterType   paramType = param.Definition.ParameterType;
                                    RVTOperations.SetFamilyParameterValue(newFamMan, param, paramType, paramStorageTypeString, paramValue, true);
                                }
                            }
                            t2.Commit();

                            //Again, do another transaction to delete the pre-existing type
                            Transaction t3 = new Transaction(newFamDoc, "DeleteOldTypes");
                            t3.Start();
                            foreach (FamilyType type in newFamMan.Types)
                            {
                                newFamMan.CurrentType = type;
                                if (newFamMan.CurrentType.Name != newType.Name)
                                {
                                    newFamMan.DeleteCurrentType();
                                }
                            }
                            t3.Commit();
                            //Save out the family and continue the loop
                            newFamDoc.SaveAs(saveDirectory + "\\" + saveName + ".rfa", saveAsOptions);
                            uiForm.multiCatCFFEFamiliesProgressBar.PerformStep();
                        }
                    }
                    // The family document is finally closed after saving off itself for each row
                    newFamDoc.Close();
                }
                else
                {
                    MessageBox.Show("No Creation Method was selected");
                }

                //Delete the _temp file
                File.Delete(tempFamilyPath);

                //Clean up the backup files too
                List <string> backupFiles = GeneralOperations.GetAllRvtBackupFamilies(uiForm.multiCatCFFEFamilySaveLocation, false);
                GeneralOperations.CleanRfaBackups(backupFiles);
            }
        }
Example #8
0
        public DataTable gettingFamilyParamenters(Document rfadoc)
        {
            DataTable openFamilyParaDataTable = new DataTable("familyParameterTable");

            //创建带列名的列
            openFamilyParaDataTable.Columns.Add("paraname", typeof(String));
            openFamilyParaDataTable.Columns.Add("paravalue", typeof(String));
            openFamilyParaDataTable.Columns.Add("paratag", typeof(String));

            if (rfadoc.IsFamilyDocument)
            {
                FamilyManager familyMgr   = rfadoc.FamilyManager;
                FamilyType    currentType = familyMgr.CurrentType;
                //Element elerfadoc = rfadoc as Element;
                //ParameterSet de = familyMgr.Parameters;

                //获取参数集
                FamilyParameterSet     rfadocParas     = rfadoc.FamilyManager.Parameters;
                List <FamilyParameter> rfadocParasList = new List <FamilyParameter>();
                // 接下来将获取的值放入DATASET
                int countNum = 0;
                foreach (FamilyParameter rfadocPara in rfadocParas)
                {
                    rfadocParasList.Add(rfadocPara);
                }
                for (int ii = 0; ii < rfadocParasList.Count(); ii++)
                {
                    if (currentType == null)
                    {
                        MessageBox.Show("NO LI");
                        break;
                    }


                    string rfadocParaName = rfadocParasList[ii].Definition.Name;
                    if (rfadocParaName != null)
                    {
                        string rfadocParaValue = currentType.AsString(rfadocParasList[ii]);
                        bool   rfadocParaTag   = rfadocParasList[ii].IsInstance;
                        openFamilyParaDataTable.Rows.Add();

                        openFamilyParaDataTable.Rows[countNum]["paraname"]  = rfadocParaName;
                        openFamilyParaDataTable.Rows[countNum]["paravalue"] = rfadocParaValue;
                        if (rfadocParaTag == true)
                        {
                            openFamilyParaDataTable.Rows[countNum]["paratag"] = "是";
                        }
                        else
                        {
                            openFamilyParaDataTable.Rows[countNum]["paratag"] = "否";
                        }
                    }
                    else
                    {
                        continue;
                    }
                    countNum++;
                }
            }
            return(openFamilyParaDataTable);
        }
Example #9
0
        public AllCatCFFE1Request(UIApplication uiApp, String text)
        {
            MainUI             uiForm      = BARevitTools.Application.thisApp.newMainUi;
            RVTDocument        doc         = uiApp.ActiveUIDocument.Document;
            DataTable          dt          = new DataTable();
            DataGridView       dgv         = uiForm.multiCatCFFEExcelDGV;
            RVTDocument        famDoc      = RVTOperations.OpenRevitFile(uiApp, Application.thisApp.newMainUi.multiCatSelectedFamilyFile);
            FamilyManager      famMan      = famDoc.FamilyManager;
            FamilyParameterSet famParamSet = famMan.Parameters;

            //The following columns are being added to the DataTable for use in the Excel template creation
            DataColumn paramSelectColumn          = dt.Columns.Add("Parameter Select", typeof(Boolean));
            DataColumn parameterNameColumn        = dt.Columns.Add("Parameter Name", typeof(String));
            DataColumn parameterGroupColumn       = dt.Columns.Add("Parameter Group", typeof(String));
            DataColumn parameterTypeColumn        = dt.Columns.Add("Parameter Type", typeof(String));
            DataColumn parameterStorageTypeColumn = dt.Columns.Add("Parameter Storage Type", typeof(String));

            //For each family parameter, get data associated with it for the DataTable
            foreach (FamilyParameter famParam in famParamSet)
            {
                string paramName        = famParam.Definition.Name;
                string paramGroup       = RVTOperations.GetNameFromBuiltInParameterGroup(famParam.Definition.ParameterGroup);
                string paramType        = famParam.Definition.ParameterType.ToString();
                string paramStorageType = famParam.StorageType.ToString();
                //Verify the parameter being evaluated is not one where the value is an element because that will not be useful without knowing the element ID ahead of time. Also, ensure the parameter is not locked by a formula, and ensure the ParameterType is valid
                if (paramStorageType.ToString() != "ElementId" && famParam.IsDeterminedByFormula == false && famParam.Definition.ParameterType != ParameterType.Invalid)
                {
                    //Pending the pass of the checks, fill out the DataTable with the parameter name, group, type, and data type
                    DataRow row = dt.NewRow();
                    row["Parameter Select"]       = false;
                    row["Parameter Name"]         = paramName;
                    row["Parameter Group"]        = paramGroup;
                    row["Parameter Type"]         = paramType;
                    row["Parameter Storage Type"] = paramStorageType;
                    dt.Rows.Add(row);
                }
            }

            //Bind the DataTable to the DataGridView
            BindingSource bs = new BindingSource();

            bs.DataSource  = dt;
            dgv.DataSource = bs;

            //Format the DataGridView and set the names for its columns so the row values can be retrieved by column name
            dgv.RowHeadersVisible = false;
            dgv.SelectionMode     = DataGridViewSelectionMode.FullRowSelect;
            dgv.Columns["Parameter Select"].Width            = 45;
            dgv.Columns["Parameter Select"].HeaderText       = "Select";
            dgv.Columns["Parameter Select"].Name             = "Parameter Select";
            dgv.Columns["Parameter Name"].Width              = 125;
            dgv.Columns["Parameter Name"].ReadOnly           = true;
            dgv.Columns["Parameter Name"].HeaderText         = "Name";
            dgv.Columns["Parameter Name"].Name               = "Parameter Name";
            dgv.Columns["Parameter Group"].Width             = 75;
            dgv.Columns["Parameter Group"].ReadOnly          = true;
            dgv.Columns["Parameter Group"].HeaderText        = "Group";
            dgv.Columns["Parameter Group"].Name              = "Parameter Group";
            dgv.Columns["Parameter Type"].Width              = 100;
            dgv.Columns["Parameter Type"].ReadOnly           = true;
            dgv.Columns["Parameter Type"].HeaderText         = "Param Type";
            dgv.Columns["Parameter Type"].Name               = "Parameter Type";
            dgv.Columns["Parameter Storage Type"].Width      = 100;
            dgv.Columns["Parameter Storage Type"].ReadOnly   = true;
            dgv.Columns["Parameter Storage Type"].HeaderText = "Data Format";
            dgv.Columns["Parameter Storage Type"].Name       = "Parameter Storage Type";

            //Sort by the Parameter Name column
            dgv.Sort(dgv.Columns["Parameter Name"], ListSortDirection.Ascending);
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            //Close the family
            famDoc.Close(false);
        }
Example #10
0
        public MaterialsCMSRequest(UIApplication uiApp, String text)
        {
            MainUI        uiForm          = BARevitTools.Application.thisApp.newMainUi;
            ProgressBar   progressBar     = uiForm.materialsCMSExcelCreateSymbolsProgressBar;
            DataGridView  dgv             = uiForm.materialsCMSExcelDataGridView;
            int           rowsCount       = dgv.Rows.Count;
            int           columnsCount    = dgv.Columns.Count;
            List <string> familyTypesMade = new List <string>();

            //Prepare the progress bar. The column count is one less because the first column is the column for family type names
            progressBar.Minimum = 0;
            progressBar.Maximum = (rowsCount) * (columnsCount - 1);
            progressBar.Step    = 1;
            progressBar.Visible = true;

            RVTDocument doc = uiApp.ActiveUIDocument.Document;

            //Reset the progress bar
            uiForm.materialsCMSExcelCreateSymbolsProgressBar.Value = 0;

            //First, try to use the family from the project. If that fails, use the family file
            Family familyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));

            //Assuming nothing went to hell in the process of loading one famiy...
            if (familyToUse != null)
            {
                //Save out the family to use
                RVTDocument tempFamDoc = doc.EditFamily(familyToUse);
                RVTOperations.SaveRevitFile(uiApp, tempFamDoc, @"C:\Temp\" + tempFamDoc.Title, true);

                //Open the family to use and get its FamilyManager
                RVTDocument   famDoc = RVTOperations.OpenRevitFile(uiApp, @"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
                FamilyManager famMan = famDoc.FamilyManager;

                //Get the parameters from the Family Manager and add them to a dictionary
                FamilyParameterSet parameters = famMan.Parameters;
                Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                foreach (FamilyParameter param in parameters)
                {
                    famParamDict.Add(param.Definition.Name, param);
                }

                //Start a new transaction to make the new family types in the family to use
                using (Transaction t1 = new Transaction(famDoc, "MakeNewTypes"))
                {
                    t1.Start();
                    //Cycle through the rows in the dgv
                    for (int i = 0; i < rowsCount; i++)
                    {
                        //The first column cell will be the type name
                        string newTypeName = dgv.Rows[i].Cells[0].Value.ToString();
                        //Get the family type names in the family
                        Dictionary <string, FamilyType> existingTypeNames = RVTOperations.GetFamilyTypeNames(famMan);
                        //If the family to make from the DGV does not exist in the dictionary keys...
                        if (!existingTypeNames.Keys.Contains(newTypeName))
                        {
                            //Make the family type and add it to the list of types made
                            FamilyType newType = famMan.NewType(newTypeName);
                            famMan.CurrentType = newType;
                            familyTypesMade.Add(newType.Name);
                        }
                        else
                        {
                            //If the type exists, set the current type it from the dictionary and add it to the list of types made
                            famMan.CurrentType = existingTypeNames[newTypeName];
                            familyTypesMade.Add(famMan.CurrentType.Name);
                        }

                        //Next, evaluate the columns that contain parameters
                        for (int j = 1; j < columnsCount; j++)
                        {
                            //The parameter names will be retrieved from the column HeaderText property
                            string paramName = dgv.Columns[j].HeaderText;
                            //Meanwhile the parameter value will come from the DGV cells
                            var paramValue = dgv.Rows[i].Cells[j].Value;

                            try
                            {
                                //If the parameter dictionary contains the parameter and the value to assign it is not empty, continue.
                                if (paramValue.ToString() != "" && famParamDict.Keys.Contains(paramName))
                                {
                                    //Get the family parameter and check if it is locked by a formula
                                    FamilyParameter param = famParamDict[paramName];
                                    if (!param.IsDeterminedByFormula)
                                    {
                                        //If it is not locked by a formula, set the parameter
                                        ParameterType paramType = param.Definition.ParameterType;
                                        RVTOperations.SetFamilyParameterValue(famMan, param, paramValue);
                                    }
                                }
                            }
                            catch
                            {; }
                            finally
                            {
                                //Always perform the step to indicate the progress.
                                progressBar.PerformStep();
                            }
                        }
                    }
                    t1.Commit();
                }

                //Use another transaction to delete the types that were not needed
                using (Transaction t2 = new Transaction(famDoc, "DeleteOldTypes"))
                {
                    t2.Start();
                    //Cycle through the family types and determine if it is in the list of types made
                    foreach (FamilyType type in famMan.Types)
                    {
                        if (!familyTypesMade.Contains(type.Name))
                        {
                            //If the type is not in the list of types made, delete it from the family file
                            famMan.CurrentType = type;
                            famMan.DeleteCurrentType();
                        }
                    }
                    t2.Commit();
                }

                //Save the family document at this point as all of the types and their parameters have been set
                famDoc.Close(true);

                using (Transaction t3 = new Transaction(doc, "LoadFamily"))
                {
                    t3.Start();
                    doc.LoadFamily(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule), new RVTFamilyLoadOptions(), out Family loadedFamily);
                    t3.Commit();
                }

                //Get the drafting view type in the project for BA Drafting View, else just get the first drafting view type
                ViewDrafting   placementView    = null;
                var            draftingViews    = new FilteredElementCollector(doc).OfClass(typeof(ViewDrafting)).WhereElementIsNotElementType().ToElements();
                ViewFamilyType draftingViewType = null;
                try
                {
                    //From the view family types collection, get the first one where its name is BA Drafting View
                    draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().Where(elem => elem.Name == "BA Drafting View").First() as ViewFamilyType;
                }
                catch
                {
                    //Well, crap. It doesn't exist. Just get the first type then and call it good.
                    draftingViewType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).WhereElementIsElementType().ToElements().First() as ViewFamilyType;
                }

                //Start a transaction for making the ID Material View and placing the family symbol types
                using (Transaction t4 = new Transaction(doc, "MakeIDMaterialView"))
                {
                    t4.Start();
                    foreach (ViewDrafting view in draftingViews)
                    {
                        //Find the view named ID Material View, or whatever jibberish someone typed in the CMS text box for the name to use. in the drafting views
                        if (view.Name == "ID Material View" || view.Name == uiForm.materialsCMSSetViewNameTextBox.Text)
                        {
                            //Delete the drafting view
                            doc.Delete(view.Id);
                            doc.Regenerate();
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    //Make a new view
                    placementView       = ViewDrafting.Create(doc, draftingViewType.Id);
                    placementView.Scale = 1;
                    if (uiForm.materialsCMSSetViewNameTextBox.Text != "")
                    {
                        //If someone defined a custom view name, use that and strip out brackets if they exist
                        placementView.Name = uiForm.materialsCMSSetViewNameTextBox.Text.Replace("{", "").Replace("}", "");
                    }
                    else
                    {
                        //Otherwise, this will be the new ID Material View
                        placementView.Name = "ID Material View";
                    }

                    try
                    {
                        //Set the view sort parameters if they exist
                        placementView.GetParameters(Properties.Settings.Default.BAViewSort1).First().Set("2 Plans");
                        placementView.GetParameters(Properties.Settings.Default.BAViewSort2).First().Set("230 Finish Plans");
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.ToString());
                    }
                    doc.Regenerate();
                    t4.Commit();
                }


                //Do magic to place each symbol in its view by calling the method below in this class
                PlaceSymbolsInView(uiApp, "ID Use", "Mark", placementView);

                //Clean up the files from the operations
                GeneralOperations.CleanRfaBackups(GeneralOperations.GetAllRvtBackupFamilies(@"C:\Temp\", false));
                File.Delete(@"C:\Temp\" + Path.GetFileName(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
                Application.thisApp.newMainUi.materialsCMSFamilyToUse = RVTGetElementsByCollection.FamilyByFamilyName(uiApp, Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule));
            }
            else
            {
                //If the family could not be found, well, let the user know of this.
                MessageBox.Show(String.Format("The {0} family could not be found in the project.",
                                              Path.GetFileNameWithoutExtension(Properties.Settings.Default.RevitFamilyMaterialsCMSSymbIdMaterialSchedule)));
            }
        }