コード例 #1
0
        // ======================================
        //   (3.1) add parameters
        // ======================================
        void addParameters()
        {
            FamilyManager mgr = _doc.FamilyManager;

            // API parameter group for Dimension is PG_GEOMETRY:
            //
            FamilyParameter paramTw = mgr.AddParameter(
                "Tw", BuiltInParameterGroup.PG_GEOMETRY,
                ParameterType.Length, false);

            FamilyParameter paramTd = mgr.AddParameter(
                "Td", BuiltInParameterGroup.PG_GEOMETRY,
                ParameterType.Length, false);

            // set initial values:
            //
            double tw = mmToFeet(150.0);
            double td = mmToFeet(150.0);

            mgr.Set(paramTw, tw);
            mgr.Set(paramTd, td);
        }
コード例 #2
0
        private bool AddSharedParameter()
        {
            // check to make sure that the file still exists and is valid
            if (File.Exists(_sharedFilePath) && null == _sharedFile)
            {
                TaskDialog.Show("Error", "SharedPARAM.txt has an invalid format.");
                return(false);
            }

            // get the Areas group from shared param file
            DefinitionGroup group = _sharedFile.Groups.get_Item(_groupName);

            if (null == group)
            {
                return(false);
            }

            // get the definition named Program Area
            ExternalDefinition def = group.Definitions.get_Item(_paramName) as ExternalDefinition;

            if (null == def)
            {
                return(false);
            }

            // check whether the parameter already exists in the document
            FamilyParameter param = _manager.get_Parameter(def.Name);

            if (null != param)
            {
                return(false);
            }

            try
            {
                // add that parameter to the current family document
                _manager.AddParameter(def, def.ParameterGroup, true);
            }
            catch (System.Exception e)
            {
                TaskDialog.Show("Error", e.Message);
                return(false);
            }

            return(true);
        }
コード例 #3
0
        public void addMaterials(Extrusion pSolid)
        {
            // We assume Material type "Glass" exists. Template "Metric Column.rft" include "Glass",
            // which in fact is the only interesting one to see the effect.
            // In practice, you will want to include in your template.
            //
            // To Do: For the exersize, create it with more appropriate ones in UI, then use the name here.
            //

            // (1)  get the materials id that we are intersted in (e.g., "Glass")
            //
            Material pMat = findElement(typeof(Material), "Glass") as Material;

            if (pMat != null)
            {
                ElementId idMat = pMat.Id;
                // (2a) this add a material to the solid base.  but then, we cannot change it for each column.
                //
                //pSolid.Parameter("Material").Set(idMat)

                // (2b) add a parameter for material finish
                //
                // this time we use instance parameter so that we can change it at instance level.
                //
                FamilyManager   pFamilyMgr        = _doc.FamilyManager;
                ForgeTypeId     builtinParamGroup = new ForgeTypeId(GroupTypeId.Materials.TypeId);
                ForgeTypeId     parametertype     = SpecTypeId.Reference.Material;
                FamilyParameter famParamFinish    = pFamilyMgr.AddParameter("ColumnFinish", builtinParamGroup, parametertype, true);

                // (2b.1) associate material parameter to the family parameter we just added
                //
                //  // 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete in Revit 2015
                //Parameter paramMat = pSolid.get_Parameter("Material");

                /// Updated for Revit 2015
                ///
                Parameter paramMat = pSolid.LookupParameter("Material");

                pFamilyMgr.AssociateElementParameterToFamilyParameter(paramMat, famParamFinish);

                // (2b.2) for our convenience, let's add another type with Glass finish
                //
                addType("Glass", 600.0, 600.0);
                pFamilyMgr.Set(famParamFinish, idMat);
            }
        }
コード例 #4
0
        private bool CreateNewParameters(Document familyDoc, Dictionary <string, Parameter> parameters)
        {
            bool result = false;

            try
            {
                FamilyManager familyManager = familyDoc.FamilyManager;

                foreach (string paramName in defDictionary.Keys)
                {
                    ExternalDefinition extDefinition   = defDictionary[paramName] as ExternalDefinition;
                    FamilyParameter    familyParam     = familyManager.AddParameter(extDefinition, BuiltInParameterGroup.INVALID, true);
                    string             originParamName = paramName.Replace("Mass_", "");
                    if (parameters.ContainsKey(originParamName))
                    {
                        Parameter param = parameters[originParamName];

                        switch (param.StorageType)
                        {
                        case StorageType.Double:
                            familyManager.Set(familyParam, param.AsDouble());
                            break;

                        case StorageType.Integer:
                            familyManager.Set(familyParam, param.AsInteger());
                            break;

                        case StorageType.String:
                            if (null != param.AsString())
                            {
                                familyManager.Set(familyParam, param.AsString());
                            }
                            break;
                        }
                    }
                }
                result = true;
                return(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create new instance parameters.\n" + ex.Message, "MassCreator:CreateNewParameters", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(result);
            }
        }
コード例 #5
0
        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);
        }
コード例 #6
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            FamilyManager famMgr = doc.FamilyManager;

            DefinitionFile   defFile = app.OpenSharedParameterFile( );
            DefinitionGroups defGrps = defFile.Groups;

            foreach (DefinitionGroup defGrp in defGrps)
            {
                var externalDef = from ExternalDefinition extDef in defGrp.Definitions select extDef;

                foreach (ExternalDefinition extDef in externalDef)
                {
                    using (Transaction tx = new Transaction(doc))
                    {
                        tx.Start("New Param");


                        FamilyParameter famParam = famMgr.AddParameter(extDef, BuiltInParameterGroup.PG_GENERAL, false);

                        tx.Commit( );
                    }
                }
            }


            //Main
            //Reference pickedObj = uidoc.Selection.PickObject(ObjectType.Element);
            //ElementId eleid = pickedObj.ElementId;
            //Element ele = doc.GetElement(eleid);



            return(Result.Succeeded);
        }
コード例 #7
0
        /// <summary>
        /// Add a new family parameter with a given name.
        /// </summary>
        /// <param name="parameterName">The name of the new family parameter.</param>
        /// <param name="parameterGroup">The name of the group to which the family parameter belongs.</param>
        /// <param name="parameterType">The name of the type of new family parameter.</param>
        /// <param name="isInstance">Indicates if the new family parameter is instance or type (true if parameter should be instance).</param>
        /// <returns>The new family parameter.</returns>
        public Elements.FamilyParameter AddParameter(string parameterName, string parameterGroup, string parameterType, bool isInstance)
        {
            // parse parameter type
            Autodesk.Revit.DB.ParameterType type;
            if (!System.Enum.TryParse <Autodesk.Revit.DB.ParameterType>(parameterType, out type))
            {
                throw new System.Exception(Properties.Resources.ParameterTypeNotFound);
            }

            // parse parameter group
            Autodesk.Revit.DB.BuiltInParameterGroup group;
            if (!System.Enum.TryParse <Autodesk.Revit.DB.BuiltInParameterGroup>(parameterGroup, out group))
            {
                throw new System.Exception(Properties.Resources.ParameterTypeNotFound);
            }

            TransactionManager.Instance.EnsureInTransaction(this.InternalDocument);
            var famParameter = FamilyManager.AddParameter(parameterName, group, type, isInstance);

            TransactionManager.Instance.TransactionTaskDone();
            return(new Elements.FamilyParameter(famParameter));
        }
コード例 #8
0
        /// <summary>
        /// The implementation of CreateFrame()
        /// </summary>
        public override void CreateFrame()
        {
            SubTransaction subTransaction = new SubTransaction(m_document);

            subTransaction.Start();

            //create sash referenceplane and exterior referenceplane
            CreateRefPlane refPlaneCreator = new CreateRefPlane();

            if (m_sashPlane == null)
            {
                m_sashPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ(0, m_wallThickness / 2 - m_windowInset, 0), new Autodesk.Revit.DB.XYZ(0, 0, 1), "Sash");
            }
            if (m_exteriorPlane == null)
            {
                m_exteriorPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ(0, m_wallThickness / 2, 0), new Autodesk.Revit.DB.XYZ(0, 0, 1), "MyExterior");
            }
            m_document.Regenerate();

            //get the wall in the document and retrieve the exterior face
            List <Wall> walls            = Utility.GetElements <Wall>(m_application, m_document);
            Face        exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);

            if (exteriorWallFace == null)
            {
                return;
            }

            //add dimension between sash reference plane and wall face,and add parameter "Window Inset",label the dimension with window-inset parameter
            Dimension       windowInsetDimension = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorWallFace);
            FamilyParameter windowInsetPara      = m_familyManager.AddParameter("Window Inset", BuiltInParameterGroup.INVALID, ParameterType.Length, false);

            m_familyManager.Set(windowInsetPara, m_windowInset);
            windowInsetDimension.FamilyLabel = windowInsetPara;

            //create the exterior frame
            double        frameCurveOffset1 = 0.075;
            CurveArray    curveArr1         = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0);
            CurveArray    curveArr2         = m_extrusionCreator.CreateCurveArrayByOffset(curveArr1, frameCurveOffset1);
            CurveArrArray curveArrArray1    = new CurveArrArray();

            curveArrArray1.Append(curveArr1);
            curveArrArray1.Append(curveArr2);
            Extrusion extFrame = m_extrusionCreator.NewExtrusion(curveArrArray1, m_sashPlane, m_wallThickness / 2 + m_wallThickness / 12, -m_windowInset);

            extFrame.SetVisibility(CreateVisibility());
            m_document.Regenerate();

            //add alignment between wall face and exterior frame face
            exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);  // Get the face again as the document is regenerated.
            Face            exteriorExtrusionFace1 = GeoHelper.GetExtrusionFace(extFrame, m_rightView, true);
            Face            interiorExtrusionFace1 = GeoHelper.GetExtrusionFace(extFrame, m_rightView, false);
            CreateAlignment alignmentCreator       = new CreateAlignment(m_document);

            alignmentCreator.AddAlignment(m_rightView, exteriorWallFace, exteriorExtrusionFace1);

            //add dimension between sash referenceplane and exterior frame face and lock the dimension
            Dimension extFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, interiorExtrusionFace1);

            extFrameWithSashPlane.IsLocked = true;
            m_document.Regenerate();

            //create the interior frame
            double     frameCurveOffset2 = 0.125;
            CurveArray curveArr3         = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0);
            CurveArray curveArr4         = m_extrusionCreator.CreateCurveArrayByOffset(curveArr3, frameCurveOffset2);

            m_document.Regenerate();

            CurveArrArray curveArrArray2 = new CurveArrArray();

            curveArrArray2.Append(curveArr3);
            curveArrArray2.Append(curveArr4);
            Extrusion intFrame = m_extrusionCreator.NewExtrusion(curveArrArray2, m_sashPlane, m_wallThickness - m_windowInset, m_wallThickness / 2 + m_wallThickness / 12);

            intFrame.SetVisibility(CreateVisibility());
            m_document.Regenerate();

            //add alignment between interior face of wall and interior frame face
            Face interiorWallFace       = GeoHelper.GetWallFace(walls[0], m_rightView, false);
            Face interiorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, false);
            Face exteriorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, true);

            alignmentCreator.AddAlignment(m_rightView, interiorWallFace, interiorExtrusionFace2);

            //add dimension between sash referenceplane and interior frame face and lock the dimension
            Dimension intFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorExtrusionFace2);

            intFrameWithSashPlane.IsLocked = true;

            //create the sill frame
            CurveArray    sillCurs       = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + frameCurveOffset1, m_sillHeight, 0);
            CurveArrArray sillCurveArray = new CurveArrArray();

            sillCurveArray.Append(sillCurs);
            Extrusion sillFrame = m_extrusionCreator.NewExtrusion(sillCurveArray, m_sashPlane, -m_windowInset, -m_windowInset - 0.1);

            m_document.Regenerate();

            //add alignment between wall face and sill frame face
            exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);  // Get the face again as the document is regenerated.
            Face sillExtFace = GeoHelper.GetExtrusionFace(sillFrame, m_rightView, false);

            alignmentCreator.AddAlignment(m_rightView, sillExtFace, exteriorWallFace);
            m_document.Regenerate();

            //set subcategories of the frames
            if (m_frameCat != null)
            {
                extFrame.Subcategory  = m_frameCat;
                intFrame.Subcategory  = m_frameCat;
                sillFrame.Subcategory = m_frameCat;
            }
            subTransaction.Commit();
        }
コード例 #9
0
        public bool BindSharedParameters(string filePath, bool isInstance)
        {
            string         filepath   = filePath;
            bool           isinstance = isInstance;
            DefinitionFile file       = null;

            m_app.SharedParametersFilename = filepath;

            try
            {
                file = m_app.OpenSharedParameterFile();
            }
            catch
            {
                MessageBox.Show("File has an invalid format.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (File.Exists(filepath) &&
                null == file)
            {
                MessageBox.Show("File has an invalid format.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            foreach (DefinitionGroup group in file.Groups)
            {
                foreach (ExternalDefinition def in group.Definitions)
                {
                    // check whether the parameter already exists in the document
                    FamilyParameter param = m_manager.get_Parameter(def.Name);
                    if (null != param)
                    {
                        continue;
                    }

                    BuiltInParameterGroup bpg = BuiltInParameterGroup.INVALID;
                    try
                    {
                        switch (def.OwnerGroup.Name)
                        {
                        case "Dimensions":
                            bpg = BuiltInParameterGroup.PG_GEOMETRY;
                            break;

                        case "Graphics":
                            bpg = BuiltInParameterGroup.PG_GRAPHICS;
                            break;

                        case "Model Properties":
                            bpg = BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES;
                            break;

                        case "Overall Legend":
                            bpg = BuiltInParameterGroup.PG_OVERALL_LEGEND;
                            break;

                        case "Electrical":
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL;
                            break;

                        case "Mechanical":
                            bpg = BuiltInParameterGroup.PG_MECHANICAL;
                            break;

                        case "Electrical - Lighting":
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL_LIGHTING;
                            break;

                        case "Identity Data":
                            bpg = BuiltInParameterGroup.PG_IDENTITY_DATA;
                            break;

                        case "Data":
                            bpg = BuiltInParameterGroup.PG_DATA;
                            break;

                        case "Electrical - Loads":
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL_LOADS;
                            break;

                        case "Mechanical - Air Flow":
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_AIRFLOW;
                            break;

                        case "Energy Analysis":
                            bpg = BuiltInParameterGroup.PG_ENERGY_ANALYSIS;
                            break;

                        case "Photometrics":
                            bpg = BuiltInParameterGroup.PG_LIGHT_PHOTOMETRICS;
                            break;

                        case "Mechanical - Loads":
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_LOADS;
                            break;

                        case "Structural":
                            bpg = BuiltInParameterGroup.PG_STRUCTURAL;
                            break;

                        case "Plumbing":
                            bpg = BuiltInParameterGroup.PG_PLUMBING;
                            break;

                        case "Green Building Properties":
                            bpg = BuiltInParameterGroup.PG_GREEN_BUILDING;
                            break;

                        case "Materials and Finishes":
                            bpg = BuiltInParameterGroup.PG_MATERIALS;
                            break;

                        case "Other":
                            bpg = BuiltInParameterGroup.INVALID;
                            break;

                        case "Construction":
                            bpg = BuiltInParameterGroup.PG_CONSTRUCTION;
                            break;

                        case "Phasing":
                            bpg = BuiltInParameterGroup.PG_PHASING;
                            break;

                        default:
                            bpg = BuiltInParameterGroup.INVALID;
                            break;
                        }

                        m_manager.AddParameter(def, bpg, isinstance);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            return(true);
        }
コード例 #10
0
        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
        }
コード例 #11
0
        private void InsertIntoProjectParameters()
        {
            DefinitionFile sharedParametersFile = null;

            sharedParametersFile = OpenSharedParametersFile(myCommandData.Application.Application);
            Dictionary <string, BuiltInParameterGroup> groupDict = new Dictionary <string, BuiltInParameterGroup>();

            groupDict = BrowserGroupDictionary();
            Category        revitCategory   = null;
            CategorySet     categorySet     = null;
            InstanceBinding instanceBinding = null;

            Autodesk.Revit.DB.Binding typeBinding = null;

            bool emptyValueFlag = false;

            foreach (DataGridViewRow row in dgvSharedParameters.Rows)
            {
                string category     = row.Cells["clmCategory"].Value.ToString();
                string binding      = row.Cells["clmBinding"].Value.ToString();
                string browserGroup = row.Cells["clmPropertiesGroup"].Value.ToString();

                if (myRevitDoc.IsFamilyDocument)
                {
                    if (binding == "" || browserGroup == "")
                    {
                        emptyValueFlag = true;
                        break;
                    }
                }
                else
                {
                    if (category == "" || binding == "" || browserGroup == "")
                    {
                        emptyValueFlag = true;
                        break;
                    }
                }
            }

            if (!emptyValueFlag)
            {
                Transaction trans = new Transaction(myRevitDoc, "Insert Parameters");

                trans.Start();

                foreach (DataGridViewRow row in dgvSharedParameters.Rows)
                {
                    string name         = row.Cells["clmParamName"].Value.ToString();
                    string group        = row.Cells["clmGroup"].Value.ToString();
                    string category     = row.Cells["clmCategory"].Value.ToString();
                    string binding      = row.Cells["clmBinding"].Value.ToString();
                    string browserGroup = row.Cells["clmPropertiesGroup"].Value.ToString();

                    if (!myRevitDoc.IsFamilyDocument)
                    {
                        revitCategory = myCommandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(category);
                        categorySet   = myCommandData.Application.Application.Create.NewCategorySet();
                        categorySet.Insert(revitCategory);
                        instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                        typeBinding     = myCommandData.Application.Application.Create.NewTypeBinding(categorySet);
                    }

                    ExternalDefinition extDef = GetSharedParameter(sharedParametersFile, group, name);

                    BuiltInParameterGroup paramGroup;

                    paramGroup = groupDict[browserGroup];

                    if (myRevitDoc.IsFamilyDocument)
                    {
                        FamilyManager fm = myRevitDoc.FamilyManager;

                        bool IsInstanceBinding = true;
                        if (binding == "Type")
                        {
                            IsInstanceBinding = false;
                        }
                        else
                        {
                            IsInstanceBinding = true;
                        }

                        fm.AddParameter(extDef, paramGroup, IsInstanceBinding);
                    }
                    else
                    {
                        BindingMap bindingMap = null;
                        bindingMap = myCommandData.Application.ActiveUIDocument.Document.ParameterBindings;

                        if (binding == "Type")
                        {
                            bindingMap.Insert(extDef, typeBinding, paramGroup);
                        }
                        else
                        {
                            bindingMap.Insert(extDef, instanceBinding, paramGroup);
                        }
                    }
                }

                trans.Commit();

                TaskDialog.Show("Insert Parameters", "The Shared Parameters were inserted successfully");
                this.Close();
            }
            else
            {
                TaskDialog td = new TaskDialog("Insert Parameters");
                td.MainInstruction = "Invalid value(s)";
                td.MainContent     = "Specify a value for Binding, Category, and Properties Group for each parameter before inserting parameters";
                td.Show();
            }
        }
コード例 #12
0
        public static void BindDefinitionsToCategories(Document doc,
                                                       Application app,
                                                       List <Definition> defList,
                                                       List <Category> catList,
                                                       BuiltInParameterGroup bipGroup,
                                                       bool isInstance)
        {
            // restart variables to 0.
            failNamesList.Clear();
            countSuccess = 0;
            namesSuccess.Clear();
            instanceOrType = isInstance == true ? instanceOrType = "Instance" : instanceOrType = "Type";

            // category set
            CategorySet catSet = app.Create.NewCategorySet();

            foreach (Category cat in catList)
            {
                catSet.Insert(cat);
            }

            using (TransactionGroup tg = new TransactionGroup(doc, "Load Shared Parameters"))
            {
                tg.Start();
                foreach (Definition def in defList)
                {
                    using (Transaction t = new Transaction(doc, "Add parameter Binding: " + def.Name))
                    {
                        t.Start();
                        try
                        {
                            // is Family?
                            if (doc.IsFamilyDocument == true)
                            {
                                try
                                {
                                    ExternalDefinition extDef = def as ExternalDefinition;
                                    FamilyManager      famMan = doc.FamilyManager;
                                    famMan.AddParameter(extDef, bipGroup, isInstance);

                                    countSuccess += 1;
                                    namesSuccess.Add(def.Name);
                                }
                                catch (Exception e)
                                {
                                    failNamesList.Add(def.Name + " (" + e.Message + ")");
                                }
                            }
                            // is project document
                            else
                            {
                                if (isInstance == true) // instance parameter
                                {
                                    ExternalDefinition extDef = def as ExternalDefinition;
                                    InstanceBinding    bind   = app.Create.NewInstanceBinding(catSet);
                                    doc.ParameterBindings.Insert(extDef, bind, bipGroup);

                                    countSuccess += 1;
                                    namesSuccess.Add(def.Name);
                                }
                                else // type parameter
                                {
                                    TypeBinding bind = app.Create.NewTypeBinding(catSet);
                                    doc.ParameterBindings.Insert(def, bind, bipGroup);

                                    countSuccess += 1;
                                    namesSuccess.Add(def.Name);
                                }
                            }
                            t.Commit();
                        }
                        catch (Exception e)
                        {
                            failNamesList.Add(def.Name + " (" + e.Message + ")");
                        }
                    }
                }
                tg.Assimilate();
            }
        }
コード例 #13
0
        private void SetParameters(UIApplication uiApp, string familyFile, ExternalDefinition externalDefinition)
        {
            try
            {
                //Get the FileInfo of the family file and then get the LastWriteTime value as a date string in MM/DD/YYYY format
                FileInfo fileInfo     = new FileInfo(familyFile);
                string   lastModified = fileInfo.LastWriteTime.ToShortDateString();

                //Open the family file
                RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, familyFile);
                if (famDoc != null)
                {
                    //Get the family manager for the family file
                    FamilyManager famMan = famDoc.FamilyManager;
                    //Get the family parameters and add them to a dictionary indexed by parameter name
                    FamilyParameter famParameter = null;
                    Dictionary <string, FamilyParameter> famParamDict = new Dictionary <string, FamilyParameter>();
                    foreach (FamilyParameter famParam in famMan.Parameters)
                    {
                        famParamDict.Add(famParam.Definition.Name, famParam);
                    }

                    //Get the number of family types because there must be at least one family type to make this work
                    FamilyTypeSet types         = famMan.Types;
                    int           numberOfTypes = types.Size;

                    Transaction t1 = new Transaction(famDoc, "SetParameters");
                    t1.Start();
                    if (numberOfTypes == 0)
                    {
                        //If the number of family types was 0, then one must be made. Thus Default is a family type created
                        try
                        {
                            famMan.NewType("Default");
                        }
                        catch { MessageBox.Show(String.Format("Could not make a default type or find any type for {0}", familyFile)); }
                    }

                    //Once the existence of a family type is confirmed, move on with determining if the version parameter already exists. If it doesn't add the parameter to the family and regenerate the document
                    if (!famParamDict.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter))
                    {
                        famParameter = famMan.AddParameter(externalDefinition, BuiltInParameterGroup.PG_IDENTITY_DATA, false);
                        famDoc.Regenerate();
                    }
                    else
                    {
                        famParameter = famParamDict[BARevitTools.Properties.Settings.Default.RevitUFVPParameter];
                    }

                    //Check to see if the value for the parameter is equal to the date last modified
                    if (famMan.CurrentType.AsString(famParameter) == lastModified)
                    {
                        //If so, roll back the transaction and just close the file.
                        t1.RollBack();
                        famDoc.Close(false);
                    }
                    else
                    {
                        //Otherwise set the formula of the version parameter to the quote encapsulated date, just like it would appear in Revit, commit it, then save.
                        famMan.SetFormula(famParameter, "\"" + lastModified + "\"");
                        t1.Commit();
                        RVTOperations.SaveRevitFile(uiApp, famDoc, true);
                    }
                }
                else
                {
                    //If the family could not be opened for any reason, let the user know
                    MessageBox.Show(String.Format("{0} could not be opened.", familyFile));
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
コード例 #14
0
        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);
        }
コード例 #15
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            string        rftPath = @"C:\ProgramData\Autodesk\RVT 2016\Family Templates\Chinese\公制柱.rft";
            UIApplication uiapp   = commandData.Application;
            Application   app     = uiapp.Application;
            UIDocument    uidoc   = commandData.Application.ActiveUIDocument;
            Document      doc     = uidoc.Document;

            Document    faDoc = app.NewFamilyDocument(rftPath);
            Transaction trans = new Transaction(faDoc, "创建族");

            trans.Start();
            FamilyManager   manager = faDoc.FamilyManager;
            FamilyParameter mfp     = manager.AddParameter("材质", BuiltInParameterGroup.PG_MATERIALS, ParameterType.Material,
                                                           false);

            CurveArrArray arry      = GetCurves();
            SketchPlane   skplane   = GetSketchPlane(faDoc);
            Extrusion     extrusion = faDoc.FamilyCreate.NewExtrusion(true, arry, skplane, 4000 / 304.8);

            faDoc.Regenerate();
            Reference topFaceRef = null;
            Options   opt        = new Options();

            opt.ComputeReferences = true;
            opt.DetailLevel       = ViewDetailLevel.Fine;
            GeometryElement gelm = extrusion.get_Geometry(opt);

            foreach (GeometryObject gobj in gelm)
            {
                if (gobj is Solid)
                {
                    Solid s = gobj as Solid;
                    foreach (FaceArray face in s.Faces)
                    {
                        if (face.ComputeNormal(new UV()).IsAlmostEqualTo(new XYZ(0, 0, 1)))
                        {
                            topFaceRef = face.Reference;
                        }
                    }
                }
            }
            View      v = GetView(faDoc);
            Reference r = GetTopLevel(faDoc);
            Dimension d = faDoc.FamilyCreate.NewAlignment(v, r, topFaceRef);

            d.IsLocked = true;
            faDoc.Regenerate();

            Parameter p = extrusion.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM);

            manager.AssociateElementParameterToFamilyParameter(p, mfp);

            trans.Commit();

            Family fa = faDoc.LoadFamily(doc);

            faDoc.Close(false);
            trans = new Transaction(doc, "创建柱");
            trans.Start();
            fa.Name = "我的柱子";
            trans.Commit();


            return(Result.Succeeded);
        }
コード例 #16
0
//		public void Rename_Shared_Parameters(string p_name,string new_name)
//		{
        ////			UIDocument uidoc = this.ActiveUIDocument;
        ////			Document CachedDoc = uidoc.Document;
//			Document doc;
//			//Application app;
//			string folder = @"F:\ECG work\ECG_Shared_Parameters\Samples\sample 1\f1";
//
//			// loop through all files in the directory
//
//			foreach (string filename in System.IO.Directory.GetFiles(folder))
//			{
//				try
//				{
//					doc = Application.OpenDocumentFile(filename);
//					if (doc.IsFamilyDocument)
//					{
//
//						Transaction trans = new Transaction(doc, "Remove Param");
//						trans.Start();
//						using(trans)
//						{
//							//ExternalDefinition extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), "CompanyName");
//							FamilyManager fm = doc.FamilyManager;
//							FamilyParameter fp = RawConvertSetToList<FamilyParameter>(fm.Parameters).
//								FirstOrDefault(e => e.Definition.Name.Equals(p_name, StringComparison.CurrentCultureIgnoreCase));
//							if (fp == null) throw new Exception("Invalid ParameterName Input!");
//							if(fp.IsShared)
//							{
//								ExternalDefinition extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), p_name);
        ////									        Guid guid = extdef.GUID;
        ////									        ParameterType type = extdef.ParameterType;
        ////									        string group_name = extdef.ParameterGroup.ToString();
//
//								//Create_SP(new_name,type,group_name);
//
        ////									        fm.ReplaceParameter(fp,"temp_test",BuiltInParameterGroup.PG_TEXT,true);
        ////									        FamilyParameter new_fp = RawConvertSetToList<FamilyParameter>(fm.Parameters).
        ////									        FirstOrDefault(e => e.Definition.Name.Equals("temp_test", StringComparison.CurrentCultureIgnoreCase));
        ////									        ExternalDefinition new_extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), new_name);
        ////									        fm.ReplaceParameter(new_fp,new_extdef,new_extdef.ParameterGroup,true);
//							}
//							trans.Commit();
//							//		doc.SaveAs(filename);
//							doc.Close(true);
//						}
//					}
//
//				}
//				catch (Autodesk.Revit.Exceptions.ArgumentNullException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.FamilyContextException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.FileAccessException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.FileNotFoundException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//				//	return;
//				}
//				catch (Autodesk.Revit.Exceptions.ApplicationException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//					return;
//				}
//				catch (SystemException ae)
//				{
//					TaskDialog.Show("Revit",ae.ToString());
//					//return;
//				}
//			}
//
//			//TaskDialog.Show("Iam","Here");
//
//		}

        /*	public static string GetParameterValue(FamilyParameter p)
         *      {
         *              switch(p.StorageType)
         *              {
         *                      case StorageType.Double:
         *                              return p.AsValueString();
         *                      case StorageType.ElementId:
         *                              return p.AsElementId().IntegerValue.ToString();
         *                      case StorageType.Integer:
         *                              return p.AsValueString();
         *                      case StorageType.None:
         *                              return p.AsValueString();
         *                      case StorageType.String:
         *                              return p.AsString();
         *                      default:
         *                              return "";
         *
         *              }
         *      }*/

        public static void Rename_Family_Parameters(List <string> full_files_name)
        {
//			UIDocument uidoc = this.ActiveUIDocument;
//			Document CachedDoc = uidoc.Document;
            Document doc;

            //Application app;
            //string folder = @"F:\ECG work\ECG_Shared_Parameters\Samples\sample 1\f1";

            // loop through all files in the directory

            foreach (string filename in full_files_name)
            {
                doc = CachedApp.OpenDocumentFile(filename);
                try
                {
                    if (doc.IsFamilyDocument)
                    {
                        Transaction trans = new Transaction(doc, "Rename Param");

                        using (trans)
                        {
                            //string s = Globals.new_name_for_rename;


                            trans.Start();
                            FamilyManager   fm = doc.FamilyManager;
                            FamilyParameter fp = RawConvertSetToList <FamilyParameter>(fm.Parameters).
                                                 FirstOrDefault(e => e.Definition.Name.Equals(Globals.parm_to_Replace, StringComparison.CurrentCultureIgnoreCase));
                            //		TaskDialog.Show("Revit","Shared Parameter !!");
                            trans.Commit();
                            if (fp.IsShared)
                            {
                                //		TaskDialog.Show("Revit",fm.Types.Size.ToString());
                                //	Element e = FilteredElementCollector(doc).OfClass(fm.CurrentType);

                                //	Parameter p = fm.Parameter(fp.Definition);
//									if (fp == null) throw new Exception("Invalid ParameterName Input!");
//									string tmp = "Parameter name: "+ fp.Definition.Name + "\n" +"Is Shared!";

                                //TaskDialog.Show("Warrning",tmp);
                                ExternalDefinition edf;
                                //	if(!Globals.all_SP_variables.Contains(fp.Definition.Name))
                                edf = Create_SP(Globals.new_name_for_rename,
                                                Globals.new_type,
                                                Globals.new_group);

                                trans.Start();
                                fm.AddParameter(edf, edf.ParameterGroup, Globals.instance_or_not);
                                //	fm.Parameter(edf.Name).Set(fp.ToString());


                                FamilyParameter fp_tmp = fm.get_Parameter(Globals.new_name_for_rename);
                                foreach (FamilyType t in fm.Types)
                                {
                                    if (t.HasValue(fp))
                                    {
                                        //TaskDialog.Show("R","Here");
                                        fm.CurrentType = t;
                                        if (fp_tmp.StorageType == StorageType.Double)
                                        {
                                            fm.Set(fp_tmp, t.AsDouble(fp).Value);
                                        }
                                        else if (fp_tmp.StorageType == StorageType.Integer)
                                        {
                                            fm.Set(fp_tmp, t.AsInteger(fp).Value);
                                        }
                                        else if (fp_tmp.StorageType == StorageType.ElementId)
                                        {
                                            fm.Set(fp_tmp, t.AsElementId(fp).IntegerValue);
                                        }
                                        else if (fp_tmp.StorageType == StorageType.String)
                                        {
                                            fm.Set(fp_tmp, t.AsString(fp));
                                        }
                                    }
                                    // TaskDialog.Show("R",);
                                }
                                //fm.Types
                                trans.Commit();

                                trans.Start();
                                fm.RemoveParameter(fp);
                                trans.Commit();
                                //	string k = "Parameter name: "+ edf.Name + "\n" +"Is Shared!";

                                //	TaskDialog.Show("Warrning",k);

                                //	fm.AddParameter();
                                //		rename_in_shared_parm_file(fp.Definition.Name,Globals.new_name_for_rename);

                                //doc.Close(false);
                                continue;
                            }
//								if (fp == null) throw new Exception("Invalid ParameterName Input!");
//								fm.RenameParameter(fp,new_name);
                            //      Test();
                            trans.Commit();

                            //ExternalDefinition extdef = RawFindExternalDefinition(Application.OpenSharedParameterFile(), "CompanyName");
//										FamilyManager fm = doc.FamilyManager;
//										FamilyParameter fp = RawConvertSetToList<FamilyParameter>(fm.Parameters).
//									        FirstOrDefault(e => e.Definition.Name.Equals(p_name, StringComparison.CurrentCultureIgnoreCase));
//									    if (fp == null) throw new Exception("Invalid ParameterName Input!");
//									    fm.RenameParameter(fp,new_name);
                            //                                      trans.Commit();
                            //		doc.SaveAs(filename);
                            doc.Close(true);
                        }
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentNullException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    //trans.Commit();
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FamilyContextException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FileAccessException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FileNotFoundException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.ApplicationException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (SystemException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //		return;
                }
            }

            //TaskDialog.Show("Iam","Here");
        }
コード例 #17
0
        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    MessageBox.Show("The Task Has Been Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else if (e.Error != null)
                {
                    MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    progressBar1.Value  = 0;
                    StatusLabel.Visible = false;
                }
                else
                {
                    RevitServices.Transactions.TransactionManager.Instance.ForceCloseTransaction();

                    var distinctItems = windowFamilies.GroupBy(x => x.Id).Select(y => y.First()); //Make List Have Only Unique Families

                    Document famDoc;

                    foreach (var item in distinctItems)
                    {
                        famDoc = localDoc.Document.EditFamily(item); //get the family property of the family
                        FamilyManager familyManager = famDoc.FamilyManager;

                        using (Transaction t = new Transaction(famDoc, "Set Parameter")) //Change Door values
                        {
                            t.Start();

                            try
                            {
                                FamilyParameter newParam = familyManager.AddParameter("Fire_Rating", BuiltInParameterGroup.PG_IDENTITY_DATA, ParameterType.Text, true);
                            }
                            catch
                            {
                                //silent catch to continue if Fire_Rating is already on a door from a previous activation
                            }


                            t.Commit();

                            LoadOpts famLoadOptions         = new LoadOpts();
                            Autodesk.Revit.DB.Family newFam = famDoc.LoadFamily(localDoc.Document, famLoadOptions);
                        }
                    }


                    using (Transaction t = new Transaction(localDoc.Document, "Set Parameter")) //Change Door values
                    {
                        t.Start();

                        foreach (var item in windowElementsDictionary)
                        {
                            ParameterSet ps = item.Key.Parameters;

                            foreach (Parameter p in ps)
                            {
                                if (p.Definition.Name == "Fire_Rating")
                                {
                                    p.Set(item.Value);
                                }
                            }
                        }


                        t.Commit();
                    }


                    MessageBox.Show("The Task Has Been Completed.", "Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    progressBar1.Value = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            DoorToWall.Enabled              = true;
            WindowToWall.Enabled            = true;
            DeleteFireRatingsDoors.Enabled  = true;
            DeleteFireRatingsWindow.Enabled = true;


            buttonCancel.Enabled = false;
            StatusLabel.Visible  = false;
        }
コード例 #18
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document famdoc = commandData.Application.ActiveUIDocument.Document;

            Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
            string oldSharedParamFilePath = app.SharedParametersFilename;

            if (!famdoc.IsFamilyDocument)
            {
                message = "Инструмнет доступен только в редакторе семейств";
                return(Result.Failed);
            }

            System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
            openDialog.Title       = "Выберите семейство-аналог";
            openDialog.Multiselect = false;

            if (openDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }

            string familyPath = openDialog.FileName;

            Document           analogFamilyDoc           = commandData.Application.Application.OpenDocumentFile(familyPath);
            ParametersInFamily pif                       = new ParametersInFamily(analogFamilyDoc);
            List <SharedParameterContainer> analogParams = pif.parameters;


            string     familyFolder = Path.GetDirectoryName(familyPath);
            string     familyTitle  = analogFamilyDoc.Title.Remove(analogFamilyDoc.Title.Length - 4);
            string     txtPath      = Path.Combine(familyFolder, familyTitle + ".txt");
            FileStream fs           = File.Create(txtPath);

            fs.Close();

            commandData.Application.Application.SharedParametersFilename = txtPath;
            DefinitionFile defFile = app.OpenSharedParameterFile();

            foreach (SharedParameterContainer spc in analogParams)
            {
                DefinitionGroup tempGroup = defFile.Groups.Create(spc.name);
                Definitions     defs      = tempGroup.Definitions;
                ExternalDefinitionCreationOptions defOptions = new ExternalDefinitionCreationOptions(spc.name, spc.intDefinition.ParameterType);
                defOptions.GUID = spc.guid;

                spc.exDefinition = defs.Create(defOptions) as ExternalDefinition;
            }

            FamilyManager fMan = famdoc.FamilyManager;

            int    c = 0, ex = 0, er = 0;
            string errMsg = "";

            foreach (SharedParameterContainer spc in analogParams)
            {
                bool checkExists = ParametersInFamily.ParamIsExists(famdoc, spc);
                if (checkExists)
                {
                    ex++;
                    continue;
                }
                try
                {
                    using (Transaction t = new Transaction(famdoc))
                    {
                        t.Start("Добавление параметров");
                        fMan.AddParameter(spc.exDefinition, spc.paramGroup, spc.isInstance);
                        t.Commit();
                    }
                    c++;
                }
                catch (Exception exc)
                {
                    er++;
                    errMsg = exc.Message;
                }
            }



            analogFamilyDoc.Close(false);
            System.IO.File.Delete(txtPath);
            app.SharedParametersFilename = oldSharedParamFilePath;

            string msg = "Успешно добавлено параметров: " + c;

            if (ex > 0)
            {
                msg += "\nУже присутствовали в семействе: " + ex;
            }
            if (er > 0)
            {
                msg += "\nНе удалось добавить: " + er + "\n" + errMsg;
            }
            TaskDialog.Show("Добавление параметров", msg);

            return(Result.Succeeded);
        }
コード例 #19
0
        public FamilyHelper(ExternalCommandData commandData)
        {
            InitializeComponent();
            this.DataContext = this;
            InitializeCommand();

            cdata = commandData;
            uiapp = commandData.Application;
            uidoc = uiapp.ActiveUIDocument;
            doc   = uidoc.Document;

            FamilyManager fm = doc.FamilyManager;

            CurrentSharedParamFile  = uiapp.Application.OpenSharedParameterFile();
            CurrentDefinitionGroups = CurrentSharedParamFile.Groups.ToList();
            #region 铝型材纠错
            var p1 = fm.get_Parameter("米重");
            var p2 = fm.get_Parameter("模图编号");

            double?v1 = 0;
            string v2 = "";
            if (p1 != null && p2 != null)
            {
                if (!p1.IsShared && !p2.IsShared)
                {
                    using (Transaction trans = new Transaction(doc, "CreateFamilyParameters"))
                    {
                        trans.Start();
                        foreach (FamilyType ft in fm.Types)
                        {
                            if (ft.HasValue(p1))
                            {
                                v1 = ft.AsDouble(p1);
                            }
                            if (ft.HasValue(p2))
                            {
                                v2 = ft.AsString(p2);
                            }
                        }
                        doc.Delete(p1.Id);
                        doc.Delete(p2.Id);

                        DefinitionFile     spfile = uiapp.Application.OpenSharedParameterFile();
                        DefinitionGroup    _grp   = spfile.Groups.get_Item("物理特性");
                        ExternalDefinition _def1  = _grp.Definitions.get_Item("米重") as ExternalDefinition;
                        ExternalDefinition _def2  = _grp.Definitions.get_Item("模图编号") as ExternalDefinition;
                        //添加参数
                        FamilyManager   familyMgr  = doc.FamilyManager;
                        bool            isInstance = false;
                        FamilyParameter paramMID   = familyMgr.AddParameter(_def2, BuiltInParameterGroup.PG_TEXT, isInstance);
                        FamilyParameter paramWPM   = familyMgr.AddParameter(_def1, BuiltInParameterGroup.INVALID, isInstance);

                        familyMgr.Set(paramMID, v2);
                        familyMgr.Set(paramWPM, (double)v1);

                        trans.Commit();

                        txtMID.Text = v2;
                        txtWPM.Text = v1.ToString();
                    }
                }
            }

            #endregion
        }
コード例 #20
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Application app = commandData.Application.Application;

            string filename = Path.Combine(_folder, _template);

            Document familyDoc = app.NewFamilyDocument(filename);

            Family family = familyDoc.OwnerFamily;

            Autodesk.Revit.Creation.FamilyItemFactory factory
                = familyDoc.FamilyCreate;

            Extrusion extrusion = null;

            using (Transaction trans = new Transaction(
                       familyDoc))
            {
                trans.Start("Create Extrusion");

                XYZ arcCenter = new XYZ(0.0, 3.0, -2.0);

                // Get the "left" view

                View view = GetView(ViewType.Elevation,
                                    XYZ.BasisY.Negate(), XYZ.BasisZ, familyDoc);

                // 2D offsets from view 'left'

                XYZ xOffset = new XYZ(0.0, 10.0, 0.0);
                XYZ yOffset = new XYZ(0.0, 0.0, -10.0);

                //################## Reference planes ################################

                // Origin's reference planes

                ReferencePlane referencePlaneOriginX
                    = factory.NewReferencePlane(XYZ.BasisX,
                                                XYZ.Zero, XYZ.BasisY, view);

                referencePlaneOriginX.Name   = "ReferencePlane_OriginX";
                referencePlaneOriginX.Pinned = true;

                ReferencePlane referencePlaneOriginY
                    = factory.NewReferencePlane(XYZ.BasisZ,
                                                XYZ.Zero, -XYZ.BasisX, view);

                referencePlaneOriginY.Name   = "ReferencePlane_OriginY";
                referencePlaneOriginY.Pinned = true;

                // Reference planes the extruded arc should stick to

                ReferencePlane referencePlaneX
                    = factory.NewReferencePlane(
                          XYZ.BasisX + yOffset,
                          XYZ.Zero + yOffset,
                          XYZ.BasisY, view);
                referencePlaneX.Name = "ReferencePlane_X";

                ReferencePlane referencePlaneY
                    = factory.NewReferencePlane(
                          XYZ.BasisZ + xOffset,
                          XYZ.Zero + xOffset,
                          -XYZ.BasisX, view);
                referencePlaneY.Name = "ReferencePlane_Y";

                familyDoc.Regenerate();

                //################## Create dimensions ###############################

                // Dimension x

                ReferenceArray refArrayX = new ReferenceArray();
                refArrayX.Append(referencePlaneX.GetReference());
                refArrayX.Append(referencePlaneOriginX.GetReference());

                Line      lineX      = Line.CreateUnbound(arcCenter, XYZ.BasisZ);
                Dimension dimensionX = factory.NewDimension(
                    view, lineX, refArrayX);

                // Dimension y

                ReferenceArray refArrayY = new ReferenceArray();
                refArrayY.Append(referencePlaneY.GetReference());
                refArrayY.Append(referencePlaneOriginY.GetReference());

                Line      lineY      = Line.CreateUnbound(arcCenter, XYZ.BasisY);
                Dimension dimensionY = factory.NewDimension(
                    view, lineY, refArrayY);

                familyDoc.Regenerate();

                //################## Create arc ######################################

                double arcRadius = 1.0;

                Arc arc = Arc.Create(
                    XYZ.Zero + xOffset + yOffset,
                    arcRadius, 0.0, 2 * Math.PI,
                    XYZ.BasisZ, XYZ.BasisY.Negate());

                CurveArray curves = new CurveArray();
                curves.Append(arc);

                CurveArrArray profile = new CurveArrArray();
                profile.Append(curves);

                Plane plane = new Plane(XYZ.BasisX.Negate(),
                                        arcCenter);

                SketchPlane sketchPlane = SketchPlane.Create(
                    familyDoc, plane);

                Debug.WriteLine("Origin: " + sketchPlane.GetPlane().Origin);
                Debug.WriteLine("Normal: " + sketchPlane.GetPlane().Normal);
                Debug.WriteLine("XVec:   " + sketchPlane.GetPlane().XVec);
                Debug.WriteLine("YVec:   " + sketchPlane.GetPlane().YVec);

                extrusion = factory.NewExtrusion(true,
                                                 profile, sketchPlane, 10);

                familyDoc.Regenerate();

                //################## Add family parameters ###########################

                FamilyManager fmgr = familyDoc.FamilyManager;

                FamilyParameter paramX = fmgr.AddParameter("X",
                                                           BuiltInParameterGroup.PG_GEOMETRY,
                                                           ParameterType.Length, true);
                dimensionX.FamilyLabel = paramX;

                FamilyParameter paramY = fmgr.AddParameter("Y",
                                                           BuiltInParameterGroup.PG_GEOMETRY,
                                                           ParameterType.Length, true);
                dimensionY.FamilyLabel = paramY;

                // Set their values

                FamilyType familyType = fmgr.NewType(
                    "Standard");

                fmgr.Set(paramX, 10);
                fmgr.Set(paramY, 10);

                trans.Commit();
            }

            // Save it to inspect

            SaveAsOptions opt = new SaveAsOptions();

            opt.OverwriteExistingFile = true;

            filename = Path.Combine(Path.GetTempPath(),
                                    "test.rfa");

            familyDoc.SaveAs(filename, opt);

            return(Result.Succeeded);
        }
コード例 #21
0
        /// <summary>
        /// Ask the user to open a revit family template and then add FamilyTypes and FamilyParameters
        /// to it. Say the user opens a Door template, he can then save the family as a new door family and load
        /// it into a new project for use.
        /// </summary>
        public void AddFamilyParameterAndType()
        {
            Document doc;

            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title  = "Select family document";
            openFileDialog.Filter = "RFT Files (*.rft)|*.rft";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                doc = m_revitApp.Application.NewFamilyDocument(openFileDialog.FileName);
            }
            else
            {
                return;
            }

            using (Transaction transaction = new Transaction(m_revitApp.ActiveUIDocument.Document))
            {
                transaction.Start("AddFamilyParameterAndType");

                if (doc.IsFamilyDocument)
                { // has to be a family document to be able to use the Family Manager.
                    FamilyManager famMgr = doc.FamilyManager;

                    //Add a family param.
                    FamilyParameter famParam = famMgr.AddParameter("RevitLookup_Param", BuiltInParameterGroup.PG_TITLE, ParameterType.Text, false);
                    famMgr.Set(famParam, "Default text.");

                    //Create a couple of new family types. Note that we can set different values for the param
                    //in different family types.

                    FamilyType newFamType = famMgr.NewType("RevitLookup_Type1");
                    famMgr.CurrentType = newFamType;

                    if (newFamType.HasValue(famParam))
                    {
                        famMgr.Set(famParam, "Text1.");
                    }

                    FamilyType newFamType1 = famMgr.NewType("RevitLookup_Type2");
                    famMgr.CurrentType = newFamType;

                    if (newFamType.HasValue(famParam))
                    {
                        famMgr.Set(famParam, "Text2.");
                    }

                    famMgr.MakeType(famParam);

                    if ((famParam != null) && (newFamType != null))
                    {
                        MessageBox.Show("New family types/params added successfully.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Family types/params addition failed.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                transaction.Commit();
            }
        }
コード例 #22
0
        public bool BindSharedParameters()
        {
            if (File.Exists(m_sharedFilePath) &&
                null == m_sharedFile)
            {
                MessageBox.Show("SharedParameter.txt has an invalid format.");
                return(false);
            }

            foreach (DefinitionGroup group in m_sharedFile.Groups)
            {
                foreach (ExternalDefinition def in group.Definitions)
                {
                    // check whether the parameter already exists in the document
                    FamilyParameter param = m_manager.get_Parameter(def.Name);
                    if (null != param)
                    {
                        continue;
                    }

                    BuiltInParameterGroup bpg = BuiltInParameterGroup.INVALID;
                    try
                    {
                        if (def.OwnerGroup.Name == "Dimensions")
                        {
                            bpg = BuiltInParameterGroup.PG_GEOMETRY;
                        }
                        else if (def.OwnerGroup.Name == "Electrical")
                        {
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL;
                        }
                        else if (def.OwnerGroup.Name == "Identity Data")
                        {
                            bpg = BuiltInParameterGroup.PG_IDENTITY_DATA;
                        }
                        else if (def.OwnerGroup.Name == "Electrical - Loads")
                        {
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL_LOADS;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical - Air Flow")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_AIRFLOW;
                        }
                        else if (def.OwnerGroup.Name == "Energy Analysis")
                        {
                            bpg = BuiltInParameterGroup.PG_ENERGY_ANALYSIS;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical - Loads")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_LOADS;
                        }
                        else if (def.OwnerGroup.Name == "Structural")
                        {
                            bpg = BuiltInParameterGroup.PG_STRUCTURAL;
                        }
                        else if (def.OwnerGroup.Name == "Plumbing")
                        {
                            bpg = BuiltInParameterGroup.PG_PLUMBING;
                        }
                        else if (def.OwnerGroup.Name == "Green Building Properties")
                        {
                            bpg = BuiltInParameterGroup.PG_GREEN_BUILDING;
                        }
                        else if (def.OwnerGroup.Name == "Materials and Finishes")
                        {
                            bpg = BuiltInParameterGroup.PG_MATERIALS;
                        }
                        else if (def.OwnerGroup.Name == "Other")
                        {
                            bpg = BuiltInParameterGroup.INVALID;
                        }
                        else if (def.OwnerGroup.Name == "Construction")
                        {
                            bpg = BuiltInParameterGroup.PG_CONSTRUCTION;
                        }
                        else
                        {
                            bpg = BuiltInParameterGroup.INVALID;
                        }

                        m_manager.AddParameter(def, bpg, false);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            return(true);
        }
コード例 #23
0
ファイル: Test_EditFamily.cs プロジェクト: sunjini/eZRvt
        private void EditFamily(Document famDoc, ExternalDefinition ExDef)
        {
            View view = famDoc.FindElement(typeof(View), targetName: "视图 1") as View;

            if (view == null)
            {
                throw new InvalidOperationException("view is null! ");
            }
            // 对于开挖土体族,其与模型土体不同的地方在于,它还是
            using (Transaction tranFam = new Transaction(famDoc))
            {
                try
                {
                    tranFam.SetName("对族文档进行修改");
                    tranFam.Start();
                    // ---------------------------------------------------------------------------------------------------------

                    // 添加参数
                    FamilyManager FM = famDoc.FamilyManager;

                    //’在进行参数读写之前,首先需要判断当前族类型是否存在,如果不存在,读写族参数都是不可行的
                    if (FM.CurrentType == null)
                    {
                        FM.NewType("CurrentType"); // 随便取个名字即可,后期会将族中的第一个族类型名称统一进行修改。
                    }

                    //
                    FamilyParameter Para_Depth;
                    Para_Depth = FM.get_Parameter("Depth");


                    FM.RemoveParameter(Para_Depth);

                    Para_Depth = FM.AddParameter(ExDef, BuiltInParameterGroup.PG_GEOMETRY, isInstance: true);

                    //' give initial values
                    // FM.Set(Para_Depth, depth); // 这里不知为何为给出报错:InvalidOperationException:There is no current type.
                    Extrusion extru = famDoc.FindElement(typeof(Extrusion)) as Extrusion;

                    // 添加标注
                    PlanarFace TopFace = GeoHelper.FindFace(extru, new XYZ(0, 0, 1));
                    PlanarFace BotFace = GeoHelper.FindFace(extru, new XYZ(0, 0, -1));

                    // make an array of references
                    ReferenceArray refArray = new ReferenceArray();
                    refArray.Append(TopFace.Reference);
                    refArray.Append(BotFace.Reference);
                    // define a demension line
                    var  a       = GeoHelper.FindFace(extru, new XYZ(0, 0, 1)).Origin;
                    Line DimLine = Line.CreateBound(TopFace.Origin, BotFace.Origin);
                    // create a dimension
                    Dimension DimDepth = famDoc.FamilyCreate.NewDimension(view, DimLine, refArray);

                    // 将深度参数与其拉伸实体的深度值关联起来
                    DimDepth.FamilyLabel = Para_Depth;

                    // famDoc.Close();
                    tranFam.Commit();
                }
                catch (Exception ex)
                {
                    // Utils.ShowDebugCatch(ex, $"事务“{tranFam.GetName()}” 出错!");
                    tranFam.RollBack();
                    throw new InvalidOperationException($"事务“{tranFam.GetName()}”出错", ex);
                }
            }
        }
コード例 #24
0
        //Create family for each building
        //http://thebuildingcoder.typepad.com/blog/2011/06/creating-and-inserting-an-extrusion-family.html
        private bool CreateFamilyFile(ProcessPolygon polygon, double height, string familyFileName, XYZ translation)
        {
            bool     success = true;
            Document FamDoc  = null;

            Autodesk.Revit.DB.Form form = null;
            using (Transaction CreateFamily = new Transaction(_doc))
            {
                CreateFamily.Start("Create a new Family");
                FamDoc = _doc.Application.NewFamilyDocument(this.FamilyTemplateAddress);
                CreateFamily.Commit();
            }
            ReferenceArray refAr = polygon.Get_ReferenceArray(FamDoc, translation);

            using (Transaction CreateExtrusion = new Transaction(FamDoc))
            {
                FailureHandlingOptions failOpt = CreateExtrusion.GetFailureHandlingOptions();
                failOpt.SetFailuresPreprocessor(new WarningSwallower());
                CreateExtrusion.SetFailureHandlingOptions(failOpt);
                CreateExtrusion.Start("Create Extrusion");
                /*Mohammad took this out of try */
                try
                {
                    form = FamDoc.FamilyCreate.NewExtrusionForm(true, refAr, height * XYZ.BasisZ);
                }
                catch (Exception)
                {
                    this.FailedAttemptsToCreateBuildings++;
                    success = false;
                }
                CreateExtrusion.Commit();
            }

            //Added by Mohammad
            using (Transaction AddParamTrans = new Transaction(FamDoc))
            {
                AddParamTrans.Start("Add Parameter");
                Autodesk.Revit.ApplicationServices.Application app = FamDoc.Application;
                View3D view3d = createView3d();

                Dimension windowInsetDimension = null;
                FaceArray faces = new FaceArray();
                if (form.IsSolid)
                {
                    Options options = new Options();
                    options.ComputeReferences = true;
                    //options.View = new Autodesk.Revit.DB.View();
                    //GeometryObjectArray geoArr = extrusion.get_Geometry(options).Objects;
                    IEnumerator <GeometryObject> Objects = form.get_Geometry(options).GetEnumerator();
                    //foreach (GeometryObject geoObj in geoArr)
                    while (Objects.MoveNext())
                    {
                        GeometryObject geoObj = Objects.Current;

                        if (geoObj is Solid)
                        {
                            Solid s = geoObj as Solid;
                            foreach (Face fc in s.Faces)
                            {
                                //MessageBox.Show(fc.ComputeNormal(new UV(0, 0)).X.ToString() + "/n" + fc.ComputeNormal(new UV(0, 0)).Y.ToString() + "/n" + fc.ComputeNormal(new UV(0, 0)).Z.ToString());
                                if (Math.Round((fc.ComputeNormal(new UV(0, 0))).Z) == 1 || Math.Round((fc.ComputeNormal(new UV(0, 0))).Z) == -1)
                                {
                                    faces.Append(fc);
                                }
                            }
                            //**************************************************************************************************************
                            //****************************Here is the Error **********************************************************************
                            //************************************************************************************************************************
                            //windowInsetDimension = AddDimension( FamDoc, view3d, faces.get_Item( 0 ), faces.get_Item( 1 ) );
                            View viewElevation = new FilteredElementCollector(FamDoc).OfClass(typeof(View)).Cast <View>().Where <View>(v => ViewType.Elevation == v.ViewType).FirstOrDefault <View>();
                            windowInsetDimension = AddDimension(FamDoc, viewElevation, faces.get_Item(0), faces.get_Item(1));
                        }
                    }
                }

                //Test for creating dimension
                #region two lines creating dimenstion
                //// first create two lines
                //XYZ pt1 = new XYZ(5, 0, 5);
                //XYZ pt2 = new XYZ(5, 0, 10);
                //Line line = Line.CreateBound(pt1, pt2);
                //Plane plane = app.Create.NewPlane(pt1.CrossProduct(pt2), pt2);

                //SketchPlane skplane = SketchPlane.Create(FamDoc, plane);

                //ModelCurve modelcurve1 = FamDoc.FamilyCreate.NewModelCurve(line, skplane);

                //pt1 = new XYZ(10, 0, 5);
                //pt2 = new XYZ(10, 0, 10);
                //line = Line.CreateBound(pt1, pt2);
                //plane = app.Create.NewPlane(pt1.CrossProduct(pt2), pt2);

                //skplane = SketchPlane.Create(FamDoc, plane);

                //ModelCurve modelcurve2 = FamDoc.FamilyCreate.NewModelCurve(line, skplane);



                //// now create a linear dimension between them
                //ReferenceArray ra = new ReferenceArray();
                //ra.Append(modelcurve1.GeometryCurve.Reference);
                //ra.Append(modelcurve2.GeometryCurve.Reference);

                //pt1 = new XYZ(5, 0, 10);
                //pt2 = new XYZ(10, 0, 10);
                //line = Line.CreateBound(pt1, pt2);


                //Dimension dim = FamDoc.FamilyCreate.NewLinearDimension(view3d, line, ra);
                #endregion

                //creates a prameter named index for each family.
                BuiltInParameterGroup paramGroup = (BuiltInParameterGroup)Enum.Parse(typeof(BuiltInParameterGroup), "PG_GENERAL");
                ParameterType         paramType  = (ParameterType)Enum.Parse(typeof(ParameterType), "Length");
                FamilyManager         m_manager  = FamDoc.FamilyManager;

                FamilyParameter famParam = m_manager.AddParameter("Height", paramGroup, paramType, true);

                //Set the value for the parameter
                if (m_manager.Types.Size == 0)
                {
                    m_manager.NewType("Type 1");
                }

                m_manager.Set(famParam, height);

                //connects dimension to lable called with
                //windowInsetDimension.FamilyLabel = famParam;

                AddParamTrans.Commit();
            }


            SaveAsOptions opt = new SaveAsOptions();
            opt.OverwriteExistingFile = true;
            FamDoc.SaveAs(familyFileName, opt);
            FamDoc.Close(false);
            return(success);
        }
コード例 #25
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            if (!doc.IsFamilyDocument)
            {
                message = "Команда доступна только в режиме редактирования семейства.";
                return(Result.Failed);
            }

            Application app = commandData.Application.Application;

            DefinitionFile defFile = app.OpenSharedParameterFile();

            if (defFile == null)
            {
                message = "Не указан файл общих параметров.";
                return(Result.Failed);
            }


            DefinitionGroups  defGroups = defFile.Groups;
            List <Definition> defs      = new List <Definition>();

            foreach (DefinitionGroup defGroup in defGroups)
            {
                List <Definition> groupDefs = defGroup.Definitions.ToList();
                defs.AddRange(groupDefs);
            }

            List <MyExParamDefinition> myDefs = defs
                                                .Select(i => new MyExParamDefinition(i))
                                                .ToList();

            myDefs.Sort();


            List <BuiltInParameterGroup> groups = Enum.GetValues(typeof(BuiltInParameterGroup)).Cast <BuiltInParameterGroup>().ToList();

            FormAddParameters form = new FormAddParameters(myDefs, groups);

            if (form.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }

            myDefs = form.defs;
            bool isInstance = form.isInstance;
            BuiltInParameterGroup paramGroup = form.selectedGroup;
            FamilyManager         fManager   = doc.FamilyManager;

            int    c = 0, e = 0;
            string errmsg = "";

            foreach (MyExParamDefinition myDef in myDefs)
            {
                try
                {
                    using (Transaction t = new Transaction(doc))
                    {
                        t.Start("Добавление параметра: " + myDef.exDef.Name);
                        ExternalDefinition exDef = myDef.exDef;
                        fManager.AddParameter(exDef, paramGroup, isInstance);
                        t.Commit();
                    }
                    c++;
                }
                catch (Exception ex)
                {
                    e++;
                    errmsg = ex.Message;
                }
            }
            string msg = "Успешно добавлено параметров: " + c;

            if (e > 0)
            {
                msg += "\nНе удалось добавить: " + e + "\n" + errmsg;
            }

            TaskDialog.Show("Отчет", msg);


            return(Result.Succeeded);
        }
コード例 #26
0
        public static void Add_SP_To_Families(List <string> full_files_name, List <string> parm_to_add, bool instance)
        {
            Document doc;

            //Application app;
            //string folder = @"F:\ECG work\ECG_Shared_Parameters\Samples\sample 1\f1";

            // loop through all files in the directory
            //	TaskDialog.Show("Revit","Hey");
            foreach (string filename in full_files_name)
            {
                doc = CachedApp.OpenDocumentFile(filename);
                try
                {
                    if (doc.IsFamilyDocument)
                    {
                        Transaction trans = new Transaction(doc, "Add Param");

                        using (trans)
                        {
                            FamilyManager    fm       = doc.FamilyManager;
                            DefinitionFile   deFile   = CachedApp.OpenSharedParameterFile();
                            DefinitionGroups myGroups = deFile.Groups;

                            foreach (string s in parm_to_add)
                            {
                                foreach (DefinitionGroup myGroup in myGroups)
                                {                                  // DefinitionGroup myGroup = myGroups.get_Item("New len");
                                    trans.Start();
                                    Definitions myDefinitions = myGroup.Definitions;
                                    //TaskDialog.Show("Revit",s);
                                    ExternalDefinition eDef = myDefinitions.get_Item(s) as ExternalDefinition;
                                    if (eDef != null)
                                    {
                                        fm.AddParameter(eDef, eDef.ParameterGroup, instance);
                                    }
                                    //TaskDialog.Show("Revit","Hey");
                                    trans.Commit();
                                    //	if(eDef != null) break;
                                }
                            }
                        }

                        //		doc.SaveAs(filename);
                        doc.Close(true);
                        //int tmp = Form1.progressBar1.Maximum;
                        //	int c = tmp/Globals.full_files_name_variables.Count;
                        //Form1.progressBar1.Increment(c);
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentNullException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    //trans.Commit();
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FamilyContextException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FileAccessException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.FileNotFoundException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (Autodesk.Revit.Exceptions.ApplicationException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //	return;
                }
                catch (SystemException ae)
                {
                    TaskDialog.Show("Revit", ae.ToString());
                    doc.Close(false);
                    //		return;
                }
            }
        }
コード例 #27
0
        public AdminFamiliesBAPRequest(UIApplication uiApp, String text)
        {
            MainUI uiForm = BARevitTools.Application.thisApp.newMainUi;

            uiForm.adminFamiliesBAPDoneLabel.Visible = false;
            RVTDocument   doc           = uiApp.ActiveUIDocument.Document;
            SaveAsOptions saveAsOptions = new SaveAsOptions();

            saveAsOptions.Compact               = true;
            saveAsOptions.MaximumBackups        = 3;
            saveAsOptions.OverwriteExistingFile = true;
            Dictionary <string, ExternalDefinition> sharedParameterDefinitions = new Dictionary <string, ExternalDefinition>();

            //Determine if the shared parameters file is accessible and try to get the shared parameters so their definition names and definitions could be added to a dictionary
            bool sharedParametersIsAccessible = true;

            try
            {
                DefinitionGroups sharedParameterGroups = uiApp.Application.OpenSharedParameterFile().Groups;
                foreach (DefinitionGroup group in sharedParameterGroups)
                {
                    foreach (ExternalDefinition definition in group.Definitions)
                    {
                        if (!sharedParameterDefinitions.Keys.Contains(definition.Name))
                        {
                            sharedParameterDefinitions.Add(definition.Name, definition);
                        }
                    }
                }
            } //If the access fails, then the shared parameters file was not accessible.
            catch { sharedParametersIsAccessible = false; }

            //Get the number of families to process from the DataGridView
            int filesToProcess = 0;

            foreach (DataGridViewRow rowCount in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
            {
                if (rowCount.Cells["Family Select"].Value.ToString() == "True")
                {
                    filesToProcess++;
                }
            }

            //Prepare the progress bar
            uiForm.adminFamiliesBAPProgressBar.Value   = 0;
            uiForm.adminFamiliesBAPProgressBar.Minimum = 0;
            uiForm.adminFamiliesBAPProgressBar.Maximum = filesToProcess;
            uiForm.adminFamiliesBAPProgressBar.Step    = 1;
            uiForm.adminFamiliesBAPProgressBar.Visible = true;

            //Stop any edits to the DataGridView of parameters to add
            uiForm.adminFamiliesBAPParametersDGV.EndEdit();
            try
            {
                foreach (DataGridViewRow row in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
                {
                    try
                    {
                        //If the checkbox for including the family in the process is not null, continue
                        if (row.Cells["Family Select"].Value != null)
                        {
                            //Grab the file path for the family
                            string        filePath      = row.Cells["Family Path"].Value.ToString();
                            List <string> famParamNames = new List <string>();
                            //If the checkbox is checked to select the family
                            if (row.Cells["Family Select"].Value.ToString() == "True")
                            {
                                //Open the family document
                                RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, filePath);
                                if (famDoc.IsFamilyDocument)
                                {
                                    //Grab the family manager and make a list of parameter names already in the family
                                    FamilyManager familyManager = famDoc.FamilyManager;
                                    foreach (FamilyParameter famParam in familyManager.Parameters)
                                    {
                                        if (!famParamNames.Contains(famParam.Definition.Name))
                                        {
                                            famParamNames.Add(famParam.Definition.Name);
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }

                                    foreach (DataGridViewRow newParamRow in uiForm.adminFamiliesBAPParametersDGV.Rows)
                                    {
                                        try
                                        {
                                            //Get the name of the parameter, group, and type of parameter to add
                                            string name = newParamRow.Cells["Parameter Name"].Value.ToString();
                                            BuiltInParameterGroup group = RVTOperations.GetBuiltInParameterGroupFromString(newParamRow.Cells["Parameter Group"].Value.ToString());
                                            ParameterType         type  = RVTOperations.GetParameterTypeFromString(newParamRow.Cells["Parameter Type"].Value.ToString());
                                            //Determine if the checkbox for making the parameter an instance parameter is checked
                                            bool isInstance = false;
                                            try
                                            {
                                                isInstance = Convert.ToBoolean(newParamRow.Cells["Parameter Is Instance"].Value.ToString());
                                            }
                                            catch { isInstance = false; }

                                            //Determine if the read-only checkbox for the parameter being a shared parameter is checked.
                                            bool isShared = false;
                                            try
                                            {
                                                isShared = Convert.ToBoolean(newParamRow.Cells["Parameter Is Shared"].Value.ToString());
                                            }
                                            catch { isShared = false; }

                                            //If the parameter is shared, and the parameter file is still accessible, and the family does not already contain a parameter with that name, continue
                                            if (isShared == true && sharedParametersIsAccessible == true && !famParamNames.Contains(name))
                                            {
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    //Get the parameter definition from the dictionary of shared parameters, then add it to the family
                                                    ExternalDefinition definition = sharedParameterDefinitions[newParamRow.Cells["Parameter Name"].Value.ToString()];
                                                    FamilyParameter    newParam   = familyManager.AddParameter(definition, group, isInstance);
                                                    try
                                                    {
                                                        //Try to assign the parameter value if one is to be assigned
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            //If the number of types is greater than 0, cycle through them
                                                            if (familyManager.Types.Size > 0)
                                                            {
                                                                foreach (FamilyType familyType in familyManager.Types)
                                                                {
                                                                    //For each type, make a subtransaction
                                                                    SubTransaction s1 = new SubTransaction(famDoc);
                                                                    s1.Start();
                                                                    try
                                                                    {
                                                                        //Then set the family type as current
                                                                        familyManager.CurrentType = familyType;
                                                                        //Attempt to set the parameter value
                                                                        RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                                        s1.Commit();
                                                                    }
                                                                    catch
                                                                    {
                                                                        //If that fails, let the user know and break out of the loop
                                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for type {2} in family {3}.", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], familyType.Name, row.Cells["Family Name"]));
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                //If there was was no family types in the family, just set it for the default one
                                                                RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                            }
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        //If assignment fails, let the user know the parameter value, parameter name, and the family where the failure occured.
                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for family {2}", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], row.Cells["Family Name"]));
                                                    }
                                                    t.Commit();
                                                }
                                            }
                                            else if (isShared == true && sharedParametersIsAccessible == false && !famParamNames.Contains(name))
                                            {
                                                //If the shared parameter file could not be accessed, let the user know
                                                MessageBox.Show(String.Format("Could not set the shared parameter {0} because the shared parameters file for this project could not be found. " +
                                                                              "Verify the shared parameters file is mapped correctly.", name));
                                            }
                                            else if (isShared != true && !famParamNames.Contains(name))
                                            {
                                                //Otherwise, just make a standard parameter
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    FamilyParameter newParam = familyManager.AddParameter(name, group, type, isInstance);
                                                    try
                                                    {
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                        }
                                                    }
                                                    catch { continue; }
                                                    t.Commit();
                                                }
                                            }
                                            else
                                            {
                                                //If all other conditions were not met, then the parameter already exists.
                                                MessageBox.Show(String.Format("Could not make parameter '{0}' for {1} because it already exists.", name, famDoc.Title));
                                            }
                                        }
                                        catch { continue; }
                                        finally
                                        {
                                            //Save the family
                                            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
                                            famDoc.SaveAs(filePath, saveAsOptions);
                                        }
                                    }
                                }
                                //Close the family
                                famDoc.Close(false);
                            }
                            else
                            {
                                continue;
                            }
                            //Step forward the progress bar
                            uiForm.adminFamiliesBAPProgressBar.PerformStep();
                        }
                    }
                    catch
                    {
                        MessageBox.Show("The family could not be opened, likely due to being saved in a newer version of Revit");
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                //Clean up the backups when done
                GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesBAPFamilyDirectory);
            }
            uiForm.adminFamiliesBAPProgressBar.Visible = false;
            uiForm.adminFamiliesBAPDoneLabel.Visible   = true;
            uiForm.Update();
        }