Beispiel #1
0
        //這個方法也是被公開在官網上的,我只是小小修改並且翻譯了註解,參考以下網址
        //http://www.revitapidocs.com/2017/f5066ef5-fa12-4cd2-ad0c-ca72ab21e479.htm
        public bool SetNewParameterToTypeWall(UIApplication app, DefinitionFile myDefinitionFile)
        {
            //在共用參數檔案當中先建立一個新的參數群組
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            DefinitionGroup  myGroup  = myGroups.Create("新參數群組");
            // 創立參數定義,含參數名稱及參數型別
            ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions("牆上塗鴉", ParameterType.Text);
            Definition myDefinition_CompanyName      = myGroup.Definitions.Create(option);
            // 創建一個類別群組,將來在這個類別群組裡的所有類別都會被新增指定的參數
            CategorySet myCategories = app.Application.Create.NewCategorySet();
            // 創建一個類別.以牆為例
            Category myCategory = Category.GetCategory(app.ActiveUIDocument.Document, BuiltInCategory.OST_Walls);

            myCategories.Insert(myCategory);//把牆類別插入類別群組,當然你可以插入不只一個類別
            //以下兩者是亮點,「類別綁定」與「實體綁定」的結果不同,以本例而言我們需要的其實是實體綁定
            //TypeBinding typeBinding = app.Application.Create.NewTypeBinding(myCategories);
            InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(myCategories);
            //取得一個叫作BingdingMap的物件,以進行後續新增參數
            BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings;
            // 最後將新增參數加到群組上頭,並且指定了instanceBiding的方法(也可替換為typeBinding)
            bool typeBindOK = bindingMap.Insert(myDefinition_CompanyName, instanceBinding,
                                                BuiltInParameterGroup.PG_TEXT);

            //bool typeBindOK=bindingMap.Insert(myDefinition_CompanyName, typeBinding,
            //BuiltInParameterGroup.PG_TEXT);
            return(typeBindOK);
        }
Beispiel #2
0
        /// <summary>
        /// 删除某个类别中的共享参数
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="groupName">参数组</param>
        /// <param name="parameterName">参数名</param>
        /// <param name="moveCategory">类别</param>
        /// <param name="isInstance">false:类别, true: 实例</param>
        /// <returns></returns>
        public bool DeleteShareParameter(Document doc, string groupName, string parameterName, Category moveCategory, bool isInstance)
        {
            bool isSuccess = false;

            if (string.IsNullOrWhiteSpace(path))
            {
                throw new Exception("无效路径");
            }
            doc.Application.SharedParametersFilename = this.path;
            DefinitionFile file = doc.Application.OpenSharedParameterFile();

            if (file == null)
            {
                throw new Exception("共享参数文件不存在");
            }
            DefinitionGroups groups = file.Groups;
            DefinitionGroup  group  = file.Groups.get_Item(groupName);

            if (group == null)
            {
                throw new Exception("参数组不存在");
            }
            Definition definition = group.Definitions.get_Item(parameterName);

            if (definition == null)
            {
                throw new Exception("共享参数不存在");
            }
            ElementBinding elementBinding = doc.ParameterBindings.get_Item(definition) as ElementBinding;
            CategorySet    set            = elementBinding.Categories;
            CategorySet    newSet         = new CategorySet();

            foreach (Category category in set)
            {
                if (category.Name != moveCategory.Name)
                {
                    newSet.Insert(category);
                }
            }

            if (isInstance)
            {
                elementBinding = doc.Application.Create.NewInstanceBinding(newSet);
            }
            else
            {
                elementBinding = doc.Application.Create.NewTypeBinding(newSet);
            }

            doc.ParameterBindings.Remove(definition);
            if (elementBinding.Categories.Size > 0)
            {
                return(doc.ParameterBindings.Insert(definition, elementBinding, BuiltInParameterGroup.PG_TEXT));
            }

            else
            {
                return(false);
            }
        }
Beispiel #3
0
        public void UpdateFields()
        {
            RVTDocument      doc = SPUiApp.ActiveUIDocument.Document;
            DefinitionFile   sharedParameterDoc = SPUiApp.Application.OpenSharedParameterFile();
            DefinitionGroups definitionGroups   = sharedParameterDoc.Groups;

            foreach (DefinitionGroup dgroup in definitionGroups)
            {
                foreach (ExternalDefinition definition in dgroup.Definitions)
                {
                    sharedParameterNames.Add(definition.Name);
                    sharedParameterGroupNames.Add(dgroup.Name);
                    sharedParameterTypeNames.Add(definition.ParameterType.ToString());
                    sharedParameterTypes.Add(definition.ParameterType);
                    sharedParameterDefinitions.Add(definition);
                    if (!sortedSharedParameterGroupNames.Keys.Contains(dgroup.Name))
                    {
                        sortedSharedParameterGroupNames.Add(dgroup.Name, dgroup.Name);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            foreach (string item in sortedSharedParameterGroupNames.Keys)
            {
                this.SharedParameterGroupComboBox.Items.Add(item);
            }
        }
Beispiel #4
0
        }         //end fun

        //這個方法也是被公開在官網上的,我只是小小修改並且翻譯了註解,參考以下網址
        //http://www.revitapidocs.com/2017/f5066ef5-fa12-4cd2-ad0c-ca72ab21e479.htm
        private void AddNewParametersToCategories(UIApplication app, DefinitionFile myDefinitionFile, BuiltInCategory category, List <string> newParameters)
        {
            //在共用參數檔案當中先建立一個新的參數群組
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            DefinitionGroup  myGroup  = myGroups.Create("使用者定義參數群組");

            // 創立參數定義,含參數名稱及參數型別

            foreach (string paraName in newParameters)
            {
                ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(paraName, ParameterType.Text);
                Definition myDefinition = myGroup.Definitions.Create(option);
                // 創建一個類別群組,將來在這個類別群組裡的所有類別都會被新增指定的參數
                CategorySet myCategories = app.Application.Create.NewCategorySet();
                // 創建一個類別.以牆為例
                Category myCategory = Category.GetCategory(app.ActiveUIDocument.Document, category);
                myCategories.Insert(myCategory);//把牆類別插入類別群組,當然你可以插入不只一個類別
                //以下兩者是亮點,「類別綁定」與「實體綁定」的結果不同,以本例而言我們需要的其實是實體綁定
                //TypeBinding typeBinding = app.Application.Create.NewTypeBinding(myCategories);
                InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(myCategories);
                //取得一個叫作BingdingMap的物件,以進行後續新增參數
                BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings;
                // 最後將新增參數加到群組上頭,並且指定了instanceBiding的方法(也可替換為typeBinding)
                bool typeBindOK = bindingMap.Insert(myDefinition, instanceBinding,
                                                    BuiltInParameterGroup.PG_TEXT);
            }
        }
Beispiel #5
0
        public static Definition GetDefinition(string name, Model.DefinitionGroupType defGroupType, ParameterType paramType)
        {
            Definition     def     = null;
            DefinitionFile defFile = revitData.Application.OpenSharedParameterFile();

            if (defFile == null)
            {
                CreateSharedParameterFile(Constant.ConstantValue.SharedParameterFileName);
                defFile = revitData.Application.OpenSharedParameterFile();
            }
            DefinitionGroups defGroups = defFile.Groups;
            var defGroup = defGroups.get_Item(defGroupType.ToString());

            if (defGroup == null)
            {
                defGroup = defGroups.Create(defGroupType.ToString());
            }
            var defs = defGroup.Definitions;

            def = defs.get_Item(name);
            if (def == null)
            {
                def = defGroup.Definitions.Create(new ExternalDefinitionCreationOptions(name, paramType)
                {
                    UserModifiable = true
                });
            }
            return(def);
        }
Beispiel #6
0
        // 定義參數與綁定類型的Function
        private bool setNewParameterToTypeWall(UIApplication app, DefinitionFile myDefinitionFile)
        {
            // 共用參數文檔中包含了Group,代表參數所屬的群組,
            // 而Group內又包含了Definition,也就是你想增加的參數,
            // 欲新增Definition首先必須新增一個Group
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            DefinitionGroup  myGroup  = myGroups.Create("參數群組");

            // 創建Definition的定義以及其儲存類型
            ExternalDefinitionCreationOptions options
                = new ExternalDefinitionCreationOptions("聯絡人", ParameterType.Text);
            Definition myDefinition = myGroup.Definitions.Create(options);

            // 創建品類集並插入牆品類到裡面
            CategorySet myCategories = app.Application.Create.NewCategorySet();

            // 使用BuiltInCategory來取得牆品類
            Category myCategory =
                app.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_Walls);

            myCategories.Insert(myCategory);

            // 根據品類創建類型綁定的物件
            TypeBinding typeBinding = app.Application.Create.NewTypeBinding(myCategories);

            // 取得當前文件中所有的類型綁定
            BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings;

            // 將客製化的參數定義綁定到文件中
            bool typeBindOK = bindingMap.Insert(myDefinition, typeBinding,
                                                BuiltInParameterGroup.PG_TEXT);

            return(typeBindOK);
        }
Beispiel #7
0
        /// <summary>
        ///This method is provided by the official website, here is the link
        ///https://www.revitapidocs.com/2019/f5066ef5-fa12-4cd2-ad0c-ca72ab21e479.htm
        /// </summary>
        /// <param name="app"></param>
        /// <param name="myDefinitionFile"></param>
        /// <returns></returns>
        public bool SetNewParameterToTypeWall(UIApplication app, DefinitionFile myDefinitionFile)
        {
            // Create a new group in the shared parameters file
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            DefinitionGroup  myGroup  = myGroups.Create("Revit API Course");
            // Create a type definition
            ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions("Note", ParameterType.Text);
            Definition myDefinition_CompanyName      = myGroup.Definitions.Create(option);
            // Create a category set and insert category of wall to it
            CategorySet myCategories = app.Application.Create.NewCategorySet();
            // Use BuiltInCategory to get category of wall
            Category myCategory = Category.GetCategory(app.ActiveUIDocument.Document, BuiltInCategory.OST_Walls);

            myCategories.Insert(myCategory);//add wall into the group. Of course, you can add multiple categories
            //Create an object of InstanceBinding according to the Categories,
            //The next line: I also provide the TypeBinding example here, but hide the code by comments
            //TypeBinding typeBinding = app.Application.Create.NewTypeBinding(myCategories);
            InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(myCategories);
            // Get the BingdingMap of current document.
            BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings;
            //Bind the definitions to the document
            bool typeBindOK = bindingMap.Insert(myDefinition_CompanyName, instanceBinding,
                                                BuiltInParameterGroup.PG_TEXT);

            //The next two lines: I also provide the TypeBinding example here, but hide the code by comments
            //bool typeBindOK=bindingMap.Insert(myDefinition_CompanyName, typeBinding,
            //BuiltInParameterGroup.PG_TEXT);
            return(typeBindOK);
        }
        private void bttnCreate_Click(object sender, EventArgs e)
        {
            Definition definition = null;

            using (Transaction trans = new Transaction(m_doc))
            {
                trans.Start("Create Shared Parameter");
                try
                {
                    defDictionary.Clear();

                    DefinitionGroups dGroups = definitionFile.Groups;
                    DefinitionGroup  dGroup  = dGroups.get_Item("HOK Mass Parameters");
                    if (null == dGroup)
                    {
                        dGroup = dGroups.Create("HOK Mass Parameters");
                    }
                    Definitions definitions = dGroup.Definitions;

                    foreach (ListViewItem item in listViewMassParameter.Items)
                    {
                        definition = definitions.get_Item("Mass_" + item.Text);
                        Parameter parameter = item.Tag as Parameter;

                        if (null == definition && null != parameter)
                        {
                            ParameterType paramType = parameter.Definition.ParameterType;
#if RELEASE2013 || RELEASE2014
                            definition = definitions.Create("Mass_" + parameter.Definition.Name, paramType);
#elif RELEASE2015
                            ExternalDefinitonCreationOptions options = new ExternalDefinitonCreationOptions("Mass_" + parameter.Definition.Name, paramType);
                            definition = definitions.Create(options);
#elif RELEASE2016
                            ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions("Mass_" + parameter.Definition.Name, paramType);
                            definition = definitions.Create(options);
#endif
                        }

                        if (!defDictionary.ContainsKey(parameter.Definition.Name))
                        {
                            defDictionary.Add(parameter.Definition.Name, definition);
                        }
                    }
                    trans.Commit();
                    this.DialogResult = DialogResult.OK;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to set shared parameters.\n" + ex.Message, "Form_Parameters:CreateButtonClick", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    trans.RollBack();
                }
            }
        }
        /// <summary>
        /// Add a new parameter, "Unique ID", to the beams and slabs
        /// The following process should be followed:
        /// Open the shared parameters file, via the Document.OpenSharedParameterFile method.
        /// Access an existing group or create a new group, via the DefinitionFile.Groups property.
        /// Access an existing or create a new external parameter definition,
        /// via the DefinitionGroup.Definitions property.
        /// Create a new Binding with the categories to which the parameter will be bound
        /// using an InstanceBinding or a TypeBinding.
        /// Finally add the binding and definition to the document
        /// using the Document.ParameterBindings object.
        /// </summary>
        /// <returns>bool type, a value that signifies  if  add parameter was successful</returns>
        public bool SetNewParameterToBeamsAndSlabs()
        {
            //Open the shared parameters file
            // via the private method AccessOrCreateExternalSharedParameterFile
            DefinitionFile informationFile = AccessOrCreateExternalSharedParameterFile();

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

            // Access an existing or create a new group in the shared parameters file
            DefinitionGroups informationCollections = informationFile.Groups;
            DefinitionGroup  informationCollection  = null;

            informationCollection = informationCollections.get_Item("MyParameters");

            if (null == informationCollection)
            {
                informationCollections.Create("MyParameters");
                informationCollection = informationCollections.get_Item("MyParameters");
            }

            // Access an existing or create a new external parameter definition
            // belongs to a specific group
            Definition information = informationCollection.Definitions.get_Item("Unique ID");

            if (null == information)
            {
                ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions = new ExternalDefinitionCreationOptions("Unique ID", Autodesk.Revit.DB.SpecTypeId.String.Text);
                informationCollection.Definitions.Create(ExternalDefinitionCreationOptions);
                information = informationCollection.Definitions.get_Item("Unique ID");
            }

            // Create a new Binding object with the categories to which the parameter will be bound
            CategorySet categories = m_revit.Application.Create.NewCategorySet();
            Category    structuralFramingCategorie = null;
            Category    floorsClassification       = null;

            // use category in instead of the string name to get category
            structuralFramingCategorie = m_revit.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_StructuralFraming);
            floorsClassification       = m_revit.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_Floors);
            categories.Insert(structuralFramingCategorie);
            categories.Insert(floorsClassification);

            InstanceBinding caseTying = m_revit.Application.Create.NewInstanceBinding(categories);

            // Add the binding and definition to the document
            bool boundResult = m_revit.ActiveUIDocument.Document.ParameterBindings.Insert(information, caseTying);

            return(boundResult);
        }
        private ExternalDefinition GetSharedParameter(DefinitionFile file, string group, string name)
        {
            DefinitionGroups myGroups = file.Groups;
            DefinitionGroup  myGroup  = myGroups.get_Item(group);

            ExternalDefinition extDef = null;

            if (myGroup != null)
            {
                extDef = myGroup.Definitions.get_Item(name) as ExternalDefinition;
            }
            return(extDef);
        }
Beispiel #11
0
        /// <summary>
        /// Gets definition groups by sharing parameter file path.
        /// </summary>
        /// <param name="groups"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public static DefinitionGroup GetGroup(this DefinitionGroups groups, string groupName)
        {
            if (groups == null)
            {
                throw new ArgumentNullException(nameof(groups));
            }

            if (groupName == null)
            {
                throw new ArgumentNullException(nameof(groupName));
            }

            return(groups.get_Item(groupName) ?? groups.Create(groupName));
        }
Beispiel #12
0
        public bool AddShadeParameter(Document doc, string groupName, string parameterName, Category category, bool isInstance)
        {
            if (this.path == "")
            {
                throw new Exception("路径无效");
            }
            doc.Application.SharedParametersFilename = this.path;
            DefinitionFile   definitionFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroups groups         = definitionFile.Groups;
            DefinitionGroup  group          = groups.get_Item(groupName);

            if (group == null)
            {
                throw new Exception("没有找到对应的参数组,组名:" + groupName);
            }
            Definition definition = group.Definitions.get_Item(parameterName);

            if (definition == null)
            {
                throw new Exception("没有找到对应的参数,参数名:" + parameterName);
            }

            ElementBinding binding = null;
            ElementBinding bind    = doc.ParameterBindings.get_Item(definition) as ElementBinding;
            CategorySet    set     = new CategorySet();;

            if (bind != null)
            {
                foreach (Category c in bind.Categories)
                {
                    set.Insert(c);
                }
            }

            var b = set.Insert(category);

            if (isInstance)
            {
                binding = doc.Application.Create.NewInstanceBinding(set);
            }
            else
            {
                binding = doc.Application.Create.NewTypeBinding(set);
            }
            doc.ParameterBindings.Remove(definition);
            return(doc.ParameterBindings.Insert(definition, binding, BuiltInParameterGroup.PG_TEXT));
        }
Beispiel #13
0
        public void AddExistingSharedParameter(string groupOfSharedParam,
                                               string name,
                                               CategorySet cats,
                                               BuiltInParameterGroup group,
                                               bool inst)

        {
            try
            {
                AplicationRvt.SharedParametersFilename = GetNewSharedParameterFilePath();
                DefinitionFile defFile = AplicationRvt.OpenSharedParameterFile();
                if (defFile == null)
                {
                    throw new Exception("No SharedParameter File!");
                }

                DefinitionGroups   myGroups = defFile.Groups;
                DefinitionGroup    myGroup  = myGroups.get_Item(groupOfSharedParam);
                ExternalDefinition def      = null;
                if (myGroup == null)
                {
                    throw new Exception("The group doesn't exist. Inspect name of group");
                }
                def = myGroup.Definitions.get_Item(name) as ExternalDefinition;
                if (def == null)
                {
                    throw new Exception("The parameter doesnt exist");
                }

                Binding binding = AplicationRvt.Create.NewTypeBinding(cats);
                if (inst)
                {
                    binding = AplicationRvt.Create.NewInstanceBinding(cats);
                }

                BindingMap map = (new UIApplication(AplicationRvt)).ActiveUIDocument.Document.ParameterBindings;
                map.Insert(def, binding, group);
                SetExistingSharedParameterFile();
            }
            finally
            {
                SetExistingSharedParameterFile();
            }
        }
Beispiel #14
0
        public static bool AddSharedParameterByDefaulGroupName(Document doc, string sharedParameterFile, string groupName, string parameterName, Category newCategory, bool isInstance, BuiltInParameterGroup parameterGroup)
        {
            doc.Application.SharedParametersFilename = sharedParameterFile;
            DefinitionFile   definitionFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroups groups         = definitionFile.Groups;
            DefinitionGroup  group          = groups.get_Item(groupName);

            if (group == null)
            {
                throw new Exception("没有找到对应的参数组");
            }
            Definition definition = group.Definitions.get_Item(parameterName);

            if (definition == null)
            {
                throw new Exception("没有找到对应的参数");
            }
            ElementBinding binding       = null;
            ElementBinding orientBinding = doc.ParameterBindings.get_Item(definition) as ElementBinding;
            CategorySet    categories    = new CategorySet();;

            if (orientBinding != null)
            {
                foreach (Category c in orientBinding.Categories)
                {
                    categories.Insert(c);
                }
            }
            categories.Insert(newCategory);
            if (isInstance)
            {
                binding = doc.Application.Create.NewInstanceBinding(categories);
            }
            else
            {
                binding = doc.Application.Create.NewTypeBinding(categories);
            }
            doc.ParameterBindings.Remove(definition);
            var result = doc.ParameterBindings.Insert(definition, binding, parameterGroup);

            return(result);
        }
Beispiel #15
0
        public static ExternalDefinition Create_SP(string sp_name
                                                   , ParameterType type, string group_name)
        {
            DefinitionFile deFile = CachedApp.OpenSharedParameterFile();
            // create new group in the shared paramters files
            DefinitionGroups groups       = deFile.Groups;
            bool             founded      = false;
            Definition       myDefinition = groups.First().Definitions.First();

            foreach (DefinitionGroup dg in groups)
            {
                if (dg.Name == group_name)
                {
                    ExternalDefinition exDef = dg.Definitions.get_Item(sp_name) as ExternalDefinition;
                    if (exDef != null)
                    {
                        //exDef.Description
                        return(exDef);
                    }
                    //ExternalDefinition exDef = dg.Definitions.get_Item("CompanyName") as ExternalDefinition;
                    ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(sp_name, type);

                    myDefinition = dg.Definitions.Create(option);

                    founded = true;
                    break;
                }
            }
            if (!founded)
            {
                DefinitionGroup myGroup = groups.Create(group_name);
                // Create a type definition
                ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(sp_name, type);
                myDefinition = myGroup.Definitions.Create(option);
            }

            ExternalDefinition eDef = myDefinition as ExternalDefinition;

            return(eDef);

            //
        }
Beispiel #16
0
        public static void PrepareSharedParameter(Document doc)
        {
            doc.Application.SharedParametersFilename = SharedParameterFile;
            if (!File.Exists(SharedParameterFile))
            {
                var fs = File.Create(SharedParameterFile);
                fs.Close();
            }
            DefinitionFile   definitionFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroups groups         = definitionFile.Groups;
            DefinitionGroup  group          = groups.get_Item(GroupName);

            if (group == null)
            {
                group = definitionFile.Groups.Create(GroupName);
                group.Definitions.Create(new ExternalDefinitionCreationOptions(CustomParameters.监测类型.ToString(), ParameterType.Text));
                group.Definitions.Create(new ExternalDefinitionCreationOptions(CustomParameters.测点编号.ToString(), ParameterType.Text));
                group.Definitions.Create(new ExternalDefinitionCreationOptions(CustomParameters.监测点.ToString(), ParameterType.Text));
            }
        }
Beispiel #17
0
        private DefinitionGroup GetSharedGroup()
        {
            string sharedParametersFile = this.GetSharedParametersFile();

            this.m_revitApp.SharedParametersFilename = sharedParametersFile;
            DefinitionFile definitionFile = this.m_revitApp.OpenSharedParameterFile();

            if (definitionFile == null)
            {
                return(null);
            }
            DefinitionGroups groups          = definitionFile.Groups;
            DefinitionGroup  definitionGroup = groups.get_Item("RDBParameters");

            if (definitionGroup == null)
            {
                groups.Create("RDBParameters");
                definitionGroup = groups.get_Item("RDBParameters");
            }
            return(definitionGroup);
        }
Beispiel #18
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);
        }
Beispiel #19
0
        public bool SetNewParameterToInstanceWall(UIApplication app, DefinitionFile myDefinitionFile)
        {
            if (myDefinitionFile == null)
            {
                throw new Exception("No SharedParameter File!");
            }
            // create a new group in the shared parameters file
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            DefinitionGroup  myGroup  = myGroups.Create("MyParameters1");

            // create an instance definition in definition group MyParameters
            ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions("Instance_ProductDate", ParameterType.Text);

            // Don't let the user modify the value, only the API
            option.UserModifiable = false;
            // Set tooltip
            option.Description = "Wall product date";
            Definition myDefinition_ProductDate = myGroup.Definitions.Create(option);

            // create a category set and insert category of wall to it
            CategorySet myCategories = app.Application.Create.NewCategorySet();
            // use BuiltInCategory to get category of wall
            Category myCategory = Category.GetCategory(app.ActiveUIDocument.Document, BuiltInCategory.OST_Walls);


            myCategories.Insert(myCategory);

            //Create an instance of InstanceBinding
            InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(myCategories);

            // Get the BingdingMap of current document.
            BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings;

            // Bind the definitions to the document
            bool instanceBindOK = bindingMap.Insert(myDefinition_ProductDate,
                                                    instanceBinding, BuiltInParameterGroup.PG_TEXT);

            return(instanceBindOK);
        }
Beispiel #20
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);
        }
        private void StoreSharedParams()
        {
            using (Transaction trans = new Transaction(doc))
            {
                trans.Start("Store Shared Parameters");
                try
                {
                    string currentAssembly = System.Reflection.Assembly.GetAssembly(this.GetType()).Location;
                    string definitionPath  = Path.GetDirectoryName(currentAssembly) + "/Resources/Mass Shared Parameters.txt";
                    m_app.SharedParametersFilename = definitionPath;
                    definitionFile = m_app.OpenSharedParameterFile();

                    FilteredElementCollector collector = new FilteredElementCollector(doc);
                    Element       element            = null;
                    List <string> activeSharedParams = new List <string>();

                    switch (massCategory)
                    {
                    case MassCategory.Rooms:
                        element            = collector.OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType().ToElements().First();
                        activeSharedParams = roomSharedParameters;
                        break;

                    case MassCategory.Areas:
                        element            = collector.OfCategory(BuiltInCategory.OST_Areas).WhereElementIsNotElementType().ToElements().First();
                        activeSharedParams = areaSharedParameters;
                        break;

                    case MassCategory.Floors:
                        element            = collector.OfCategory(BuiltInCategory.OST_Floors).WhereElementIsNotElementType().ToElements().First();
                        activeSharedParams = floorSharedParameters;
                        break;
                    }

                    if (null != definitionFile)
                    {
                        DefinitionGroups dGroups = definitionFile.Groups;
                        DefinitionGroup  dGroup  = dGroups.get_Item("HOK Mass Parameters");
                        if (null == dGroup)
                        {
                            dGroup = dGroups.Create("HOK Mass Parameters");
                        }
                        Definitions definitions = dGroup.Definitions;
                        Definition  definition;

                        foreach (string paramName in activeSharedParams)
                        {
                            definition = definitions.get_Item("Mass_" + paramName);
                            if (null == definition)
                            {
#if RELEASE2013 || RELEASE2014
                                Parameter param = element.get_Parameter(paramName);
                                definition = definitions.Create("Mass_" + param.Definition.Name, param.Definition.ParameterType);
#elif RELEASE2015
                                Parameter param = element.LookupParameter(paramName);
                                ExternalDefinitonCreationOptions options = new ExternalDefinitonCreationOptions("Mass_" + param.Definition.Name, param.Definition.ParameterType);
                                definition = definitions.Create(options);
#elif RELEASE2016
                                Parameter param = element.LookupParameter(paramName);
                                ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions("Mass_" + param.Definition.Name, param.Definition.ParameterType);
                                definition = definitions.Create(options);
#endif
                            }
                            if (null != definition && !defDictionary.ContainsKey(paramName))
                            {
                                defDictionary.Add(paramName, definition);
                            }
                        }
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to store shared parameters.\n" + ex.Message, "Form_RoomMass:StoreSharedParams", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    trans.RollBack();
                }
            }
        }
Beispiel #22
0
        public AdminFamiliesUFVPRequest(UIApplication uiApp, String text)
        {
            MainUI      uiForm = BARevitTools.Application.thisApp.newMainUi;
            RVTDocument doc    = uiApp.ActiveUIDocument.Document;

            //Clear out the backup families from the directory
            List <string> backupFamilies = GeneralOperations.GetAllRvtBackupFamilies(uiForm.adminFamiliesUFVPDirectoryTextBox.Text, true);

            GeneralOperations.CleanRfaBackups(backupFamilies);

            //Get the family files from the directory. If the option to use the date since last modified was checked, use the first method, else use the second method
            List <string> familyFiles = new List <string>();

            if (uiForm.adminFamiliesUFVPCheckBox.Checked)
            {
                familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesUFVPDirectoryTextBox.Text, uiForm.adminFamiliesUFVPDatePicker.Value, true);
            }
            else
            {
                familyFiles = GeneralOperations.GetAllRvtFamilies(uiForm.adminFamiliesUFVPDirectoryTextBox.Text, false);
            }

            //Verify the number of families collected is more than 0
            if (familyFiles.Count > 0)
            {
                try
                {
                    //Make a dictionary of the shared parameter names and definitions for use later.
                    Dictionary <string, ExternalDefinition> sharedParameterDefinitions = new Dictionary <string, ExternalDefinition>();
                    DefinitionFile definitionFile = null;
                    bool           sharedParametersIsAccessible = true;
                    try
                    {
                        definitionFile = uiApp.Application.OpenSharedParameterFile();
                        DefinitionGroups sharedParameterGroups = definitionFile.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 shared parameters file is not accessible, set to false
                    catch { sharedParametersIsAccessible = false; }

                    //Reset and prepare the progress bar
                    uiForm.adminFamiliesUFVPProgressBar.Value   = 0;
                    uiForm.adminFamiliesUFVPProgressBar.Minimum = 0;
                    uiForm.adminFamiliesUFVPProgressBar.Maximum = familyFiles.Count;
                    uiForm.adminFamiliesUFVPProgressBar.Step    = 1;
                    uiForm.adminFamiliesUFVPProgressBar.Visible = true;

                    //Only proceed if the shared parameters file was accessible and the version parameter exists in the shared parameters
                    if (sharedParametersIsAccessible && sharedParameterDefinitions.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter))
                    {
                        foreach (string familyFile in familyFiles)
                        {
                            //The AdminFamiliesUFVPRequest.SetParameters() method will set the parameter value
                            SetParameters(uiApp, familyFile, sharedParameterDefinitions[Properties.Settings.Default.RevitUFVPParameter]);
                            uiForm.adminFamiliesUFVPProgressBar.PerformStep();
                        }
                    }
                    //If the shared parameter does not exist, let the user know. It will need to be made first
                    else if (sharedParametersIsAccessible && !sharedParameterDefinitions.Keys.Contains(BARevitTools.Properties.Settings.Default.RevitUFVPParameter))
                    {
                        MessageBox.Show(String.Format("Could not get the shared parameter '{0}' in the shared parameters file located at {1}. Please verify its existence", Properties.Settings.Default.RevitUFVPParameter, definitionFile.Filename));
                    }
                    //If the shared parameters file itself could not be accessed, inform the user.
                    else
                    {
                        MessageBox.Show("Could not open the shared parameters file. Verify it is loaded in the Manage Tab > Shared Parameters");
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                finally
                {
                    //Go back through the directory where the families are located and clean up the backups made from saving them after the parameter value was set.
                    List <string> backupFamilies2 = GeneralOperations.GetAllRvtBackupFamilies(uiForm.adminFamiliesUFVPDirectoryTextBox.Text, true);
                    GeneralOperations.CleanRfaBackups(backupFamilies2);
                }
            }
        }
Beispiel #23
0
 /// <summary>
 /// Gets definition groups by sharing parameter file path.
 /// </summary>
 /// <param name="groups"></param>
 /// <param name="groupName"></param>
 /// <returns></returns>
 public static DefinitionGroup GetGroup(this DefinitionGroups groups, string groupName)
 {
     return(groups.get_Item(groupName) ?? groups.Create(groupName));
 }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //String Builder
            StringBuilder sb = new StringBuilder();

            // Application context.
            UIApplication uiapp = commandData.Application;
            Application   app   = uiapp.Application;
            var           uidoc = commandData.Application.ActiveUIDocument;
            var           doc   = uidoc.Document;

            //Shared parameter file
            string oldlFile = app.SharedParametersFilename;
            string newFile  = @"C:\RenameSharedParameters\FAC_shared_parameters.txt";

            app.SharedParametersFilename = newFile;
            DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();

            //Shared parameter group settings
            DefinitionGroups defGroups = sharedParameterFile.Groups;

            sb.Append(defGroups.Size + "\n");

            DefinitionGroup defGroup = defGroups.get_Item("Facedo");


            FamilyManager fman = doc.FamilyManager;

            using (Transaction tx = new Transaction(doc, "to family parameter"))
            {
                tx.Start();

                foreach (FamilyParameter p in fman.Parameters)
                {
                    if (p.Definition.Name.Contains("MDK"))
                    {
                        try
                        {
                            fman.ReplaceParameter(p, p.Definition.Name.Replace("MDK", "TEMP"), p.Definition.ParameterGroup, p.IsInstance);

                            sb.Append(p.Definition.Name + "\n");
                        }
                        catch { }
                    }
                }

                tx.Commit();
            }

            sb.Append("\n");

            using (Transaction tx = new Transaction(doc, "to shared parameter"))
            {
                tx.Start();

                foreach (FamilyParameter p in fman.Parameters)
                {
                    if (p.Definition.Name.Contains("TEMP"))
                    {
                        try
                        {
                            string newname = p.Definition.Name.Replace("TEMP", "FAC");

                            ExternalDefinitionCreationOptions opt = new ExternalDefinitionCreationOptions(newname, p.Definition.ParameterType);

                            defGroup.Definitions.Create(opt);

                            ExternalDefinition newExtDef = defGroup.Definitions.get_Item(newname) as ExternalDefinition;

                            fman.ReplaceParameter(p, newname, p.Definition.ParameterGroup, p.IsInstance);

                            sb.Append(p.Definition.Name + "\n");
                        }
                        catch { }
                    }
                }

                tx.Commit();
            }

            TaskDialog.Show("Final Dialog", sb.ToString());

            return(Result.Succeeded);
        }
Beispiel #25
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)

        {
            //Get application and documnet objects

            UIApplication uiApp = commandData.Application;
            Document      doc   = uiApp.ActiveUIDocument.Document;
            Application   app   = doc.Application;

            try
            {
                //DO KLASY readSP
                //Open Shared Parameter file and collect SharedParam ExteralDefinition
                List <ExternalDefinition> spFileExternalDef = new List <ExternalDefinition>();
                DefinitionFile            spFile            = doc.Application.OpenSharedParameterFile();
                DefinitionGroups          gr = spFile.Groups;

                foreach (DefinitionGroup dG in gr)
                {
                    foreach (ExternalDefinition eD in dG.Definitions)
                    {
                        spFileExternalDef.Add(eD);
                    }
                }
                //@DO KLASY
                //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

                //TODO:DO KLASY readExcel
                //Load ExcelFile and Categories to assign
                string spFileName    = spFile.Filename;
                string excelFileName = "";
                TaskDialog.Show("Info", "Wybierz plik excel z kategoriami przypisaymi do parametrów");

                WF.OpenFileDialog openFileDialog1 = new WF.OpenFileDialog();

                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.Filter           = "Excel files (*.xlsx;*.xlsm;*.xls)|.xlsx;*.xlsm;*.xls";
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == WF.DialogResult.OK)
                {
                    excelFileName = openFileDialog1.FileName;
                }

                Excel.Application xlApp       = new Excel.Application();
                Excel.Workbook    xlWorkbook  = xlApp.Workbooks.Open(excelFileName);
                Excel._Worksheet  xlWorksheet = xlWorkbook.Sheets[1];
                Excel.Range       xlRange     = xlWorksheet.UsedRange;

                int rowCount = xlRange.Rows.Count;
                int colCount = xlRange.Columns.Count;
                List <List <string> > categoryListFromExcel = new List <List <string> >();

                //wartości odejmowane od iteratorów wynikają z konstrukcji przykłądowego excela -> łatwiej opóścić od razu niepotrzebne kolumny i wiersze
                for (int i = 8; i <= rowCount; i++)
                {
                    List <string> sublist = new List <string>();
                    for (int j = 11; j <= colCount; j++)
                    {
                        sublist.Add(xlRange.Cells[i, j].Value);
                        sublist.RemoveAll(item => item == null);
                    }
                    categoryListFromExcel.Add(sublist);
                }

                //cleanup
                GC.Collect();
                GC.WaitForPendingFinalizers();

                //rule of thumb for releasing com objects:
                //  never use two dots, all COM objects must be referenced and released individually
                //  ex: [somthing].[something].[something] is bad

                //release com objects to fully kill excel process from running in the background
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);

                //close and release
                xlWorkbook.Close();
                Marshal.ReleaseComObject(xlWorkbook);

                //quit and release
                xlApp.Quit();
                Marshal.ReleaseComObject(xlApp);
                //@DO KLASY readExcel
                //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

                //TODO:DO KLASY category list
                Categories categories = doc.Settings.Categories;

                SortedList <string, Category> allCategories = new SortedList <string, Category>();

                foreach (Category c in categories)
                {
                    allCategories.Add(c.Name, c);
                }

                List <List <Category> > categoryList = new List <List <Category> >();
                foreach (List <string> sub in categoryListFromExcel)
                {
                    List <Category> sublist = new List <Category>();
                    foreach (string cat in sub)
                    {
                        sublist.Add(allCategories[cat]);
                    }
                    categoryList.Add(sublist);
                }

                //@DO KLASY category list
                //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
                //TODO:(3) generalnie to trzeba dodać jeszcze iterator do wyboru pomiędzy parametrem Type i Instance i ewentualnie grupę do któej ma zostać dodany parametr
                //TODO:(3) trzeba zobaczyc co jest z ... Array group = Enum.GetValues(typeof(BuiltInParameterGroup));
                Transaction trans = new Transaction(doc, "Dodanie SP");

                trans.Start();

                List <CategorySet> catSetList = new List <CategorySet>();
                BindingMap         bindMap    = doc.ParameterBindings;
                for (int i = 0; i < spFileExternalDef.Count; i++)
                {
                    CategorySet catSet = app.Create.NewCategorySet();
                    foreach (Category n in categoryList[i])
                    {
                        catSet.Insert(n);
                    }
                    InstanceBinding bind = app.Create.NewInstanceBinding(catSet);

                    Array group = Enum.GetValues(typeof(BuiltInParameterGroup));

                    var allSomeEnumValues     = (BuiltInParameterGroup[])Enum.GetValues(typeof(BuiltInParameterGroup));
                    BuiltInParameterGroup hgs = allSomeEnumValues[97];


                    bindMap.Insert(spFileExternalDef[i], bind);
                }

                trans.Commit();

                TaskDialog.Show("Info", "Dodanie parametrów współdzielonych zostało zakończone");
                return(Result.Succeeded);
            }

            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                // If user decided to cancel the operation return Result.Canceled
                return(Result.Cancelled);
            }
            catch (Exception ex)
            {
                // If something went wrong return Result.Failed
                message = ex.Message;
                return(Result.Failed);
            }
        }
Beispiel #26
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            Application   app   = uiapp.Application;

            if (commandData.Application.ActiveUIDocument.Document.IsFamilyDocument)
            {
                DefinitionFile   sharedParameterFile = app.OpenSharedParameterFile();
                DefinitionGroups sharGroups          = sharedParameterFile.Groups;

                foreach (var sharGroup in sharGroups)
                {
                    SharedGroupDto sharGrupDto = new SharedGroupDto();
                    sharGrupDto.Name = sharGroup.Name;
                    foreach (var sharParam in sharGroup.Definitions)
                    {
                        SharedParameterDto sharedParameterDto = new SharedParameterDto();
                        sharedParameterDto.Name = (sharParam as ExternalDefinition).Name;
                        sharedParameterDto.ParameterGroupDto = (sharParam as ExternalDefinition).ParameterGroup;
                        sharedParameterDto.ParameterTypeDto  = (sharParam as ExternalDefinition).ParameterType;
                        sharedParameterDto.GUID           = (sharParam as ExternalDefinition).GUID.ToString();
                        sharedParameterDto.DescriptionDto = (sharParam as ExternalDefinition).Description;
                        sharedParameterDto.GroupName      = sharGroup.Name;
                        sharGrupDto.SharedParametersDto.Add(sharedParameterDto);
                    }
                    sharedGroupsDtos.Add(sharGrupDto);
                }
            }

            var builtInPramGroup = (BuiltInParameterGroup[])Enum.GetValues(typeof(BuiltInParameterGroup));
            List <BuiltInParameterGroup> bipg = new List <BuiltInParameterGroup>();

            foreach (var _param in builtInPramGroup)
            {
                var dsfdf = doc.FamilyManager.IsUserAssignableParameterGroup(_param);
                if (dsfdf == true)
                {
                    bipg.Add(_param);
                }
            }

            ExEventAddParameters._paramsGroup = bipg;

            List <string> builtInPramGroupValue       = new List <string>();
            Dictionary <string, string> dicParamGroup = new Dictionary <string, string>();

            foreach (var item in builtInPramGroup)
            {
                if (doc.FamilyManager.IsUserAssignableParameterGroup(item) == true)
                {
                    dicParamGroup.Add(item.ToString(), LabelUtils.GetLabelFor(item));
                }
            }
            foreach (var dir in dicParamGroup)
            {
                builtInPramGroupValue.Add(dir.Value);
            }
            SharedParameterDto.BuiltInParamGroupName = builtInPramGroupValue;

            ExEventAddParameters._paramsName = dicParamGroup;

            MainWindow          mainWindow          = new MainWindow();
            MainWindowViewModel mainWindowViewModel = new MainWindowViewModel(sharedGroupsDtos);

            mainWindowViewModel.exEventAddParameters = ExternalEvent.Create(new ExEventAddParameters(uiapp));
            mainWindow.DataContext = mainWindowViewModel;
            mainWindow.Show();


            return(Result.Succeeded);
        }
Beispiel #27
0
        private static string CreateProjectParameters(Application app, Document doc, List <Category> RevitCategories, List <string> Parameters, string GroupName)
        {
            int newParameters = 0;
            int newCategories = 0;

            CategorySet tempCategorySet = app.Create.NewCategorySet();

            foreach (Category item in RevitCategories)
            {
                IList <Element> fec = new FilteredElementCollector(doc).OfCategoryId(item.Id).WhereElementIsNotElementType().ToElements();

                if (fec.Count > 0)
                {
                    tempCategorySet.Insert(item);
                }
            }

            //get the parameter file
            string sharedParameterFile = doc.Application.SharedParametersFilename;

            DefinitionGroups existingGroups = app.OpenSharedParameterFile().Groups;

            DefinitionGroup groupName = existingGroups.get_Item(GroupName);

            if (existingGroups.get_Item(GroupName) == null)
            {
                groupName = existingGroups.Create(GroupName); //store under Data
            }

            try
            {
                foreach (string name in Parameters)
                {
                    if (!tempCategorySet.IsEmpty)
                    {
                        //shared parameter does not exist
                        if (groupName.Definitions.get_Item(name) == null)
                        {
                            InstanceBinding newInstanceBinding = app.Create.NewInstanceBinding(tempCategorySet); //cats

                            ExternalDefinition externalDefinition = groupName.Definitions.Create(new ExternalDefinitionCreationOptions(name, ParameterType.Text)) as ExternalDefinition;

                            doc.ParameterBindings.Insert(externalDefinition, newInstanceBinding, BuiltInParameterGroup.PG_DATA);

                            newParameters++;
                        }
                        //shared parameter exists
                        else
                        {
                            ExternalDefinition existingDefinition = groupName.Definitions.get_Item(name) as ExternalDefinition;

                            ElementBinding binding = doc.ParameterBindings.get_Item(existingDefinition) as ElementBinding;

                            //additional categories added to an existing shared parameter (re-insert)
                            if (binding != null)
                            {
                                foreach (Category item in binding.Categories)
                                {
                                    tempCategorySet.Insert(item);
                                }

                                InstanceBinding newInstanceBinding = app.Create.NewInstanceBinding(tempCategorySet); //cats

                                doc.ParameterBindings.ReInsert(existingDefinition, newInstanceBinding, BuiltInParameterGroup.PG_DATA);

                                newCategories++;
                            }
                            //shared parameter exists but has never been inserted (if the user undo the operation)
                            else
                            {
                                InstanceBinding newInstanceBinding = app.Create.NewInstanceBinding(tempCategorySet); //cats

                                doc.ParameterBindings.Insert(existingDefinition, newInstanceBinding, BuiltInParameterGroup.PG_DATA);

                                newCategories++;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
            finally
            {
                app.SharedParametersFilename = sharedParameterFile;
            }

            //File.Delete(tempSharedParameterFile);

            return($"Parameters created: {newParameters}\nParameters categories updated: {newCategories}");
        }
Beispiel #28
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;
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Add shared parameters needed in this sample.
        /// parameter 1: one string parameter named as "BasalOpening" which  is used for customization of door opening for each country.
        /// parameter 2: one string parameter named as "InstanceOpening" to indicate the door's opening value.
        /// parameter 3: one YESNO parameter named as "Internal Door" to flag the door is internal door or not.
        /// </summary>
        /// <param name="app">Revit application.</param>
        public static void AddSharedParameters(UIApplication app)
        {
            // Create a new Binding object with the categories to which the parameter will be bound.
            CategorySet categories = app.Application.Create.NewCategorySet();

            // get door category and insert into the CategorySet.
            Category doorCategory = app.ActiveUIDocument.Document.Settings.Categories.
                                    get_Item(BuiltInCategory.OST_Doors);

            categories.Insert(doorCategory);

            // create one instance binding for "Internal Door" and "InstanceOpening" parameters;
            // and one type binding for "BasalOpening" parameters
            InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(categories);
            TypeBinding     typeBinding     = app.Application.Create.NewTypeBinding(categories);
            BindingMap      bindingMap      = app.ActiveUIDocument.Document.ParameterBindings;

            // Open the shared parameters file
            // via the private method AccessOrCreateSharedParameterFile
            DefinitionFile defFile = AccessOrCreateSharedParameterFile(app.Application);

            if (null == defFile)
            {
                return;
            }

            // Access an existing or create a new group in the shared parameters file
            DefinitionGroups defGroups = defFile.Groups;
            DefinitionGroup  defGroup  = defGroups.get_Item("DoorProjectSharedParameters");

            if (null == defGroup)
            {
                defGroup = defGroups.Create("DoorProjectSharedParameters");
            }

            // Access an existing or create a new external parameter definition belongs to a specific group.

            // for "BasalOpening"
            if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "BasalOpening", BuiltInCategory.OST_Doors))
            {
                Definition basalOpening = defGroup.Definitions.get_Item("BasalOpening");

                if (null == basalOpening)
                {
                    basalOpening = defGroup.Definitions.Create("BasalOpening", ParameterType.Text, false);
                }

                // Add the binding and definition to the document.
                bindingMap.Insert(basalOpening, typeBinding, BuiltInParameterGroup.PG_GEOMETRY);
            }



            // for "InstanceOpening"
            if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "InstanceOpening", BuiltInCategory.OST_Doors))
            {
                Definition instanceOpening = defGroup.Definitions.get_Item("InstanceOpening");

                if (null == instanceOpening)
                {
                    instanceOpening = defGroup.Definitions.Create("InstanceOpening", ParameterType.Text, true);
                }

                // Add the binding and definition to the document.
                bindingMap.Insert(instanceOpening, instanceBinding, BuiltInParameterGroup.PG_GEOMETRY);
            }

            // for "Internal Door"
            if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "Internal Door", BuiltInCategory.OST_Doors))
            {
                Definition internalDoorFlag = defGroup.Definitions.get_Item("Internal Door");

                if (null == internalDoorFlag)
                {
                    internalDoorFlag = defGroup.Definitions.Create("Internal Door", ParameterType.YesNo, true);
                }

                // Add the binding and definition to the document.
                bindingMap.Insert(internalDoorFlag, instanceBinding);
            }
        }
Beispiel #30
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();
        }