示例#1
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);
            }
        }
示例#2
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);
        }
示例#3
0
        private void TransactionCommit(Document doc, ExternalDefinition def, Autodesk.Revit.DB.Binding binding, BuiltInParameterGroup group)
        {
            using (Transaction transNew = new Transaction(doc, "Create project parameter"))
            {
                try
                {
                    transNew.Start();

                    BindingMap map = doc.ParameterBindings;

                    if (SelectParameters.OverwriteParam == true)
                    {
                        map.ReInsert(def, binding, group);
                    }

                    map.Insert(def, binding, group);
                }


                catch (Exception e)
                {
                    transNew.RollBack();
                    MessageBox.Show(e.ToString());
                }

                transNew.Commit();
            }
        }
示例#4
0
        public static void sharedParameterEkle(RevitApplication app, string name, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            DefinitionFile defFile = app.OpenSharedParameterFile();

            if (defFile == null)
            {
                throw new Exception("No SharedParameter File!");
            }
            var v = (from DefinitionGroup dg in defFile.Groups
                     from ExternalDefinition d in dg.Definitions
                     where d.Name == name
                     select d);

            if (v == null || v.Count() < 1)
            {
                throw new Exception("Invalid Name Input!");
            }
            ExternalDefinition def = v.First();

            Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats);
            if (inst)
            {
                binding = app.Create.NewInstanceBinding(cats);
            }
            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;

            map.Insert(def, binding, group);
        }
示例#5
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);
        }
示例#6
0
        private void AddSharedParameters(Application app, Document doc)
        {
            //Save the previous shared param file path
            string previousSharedParam = app.SharedParametersFilename;

            //Extract shared param to a txt file
            string tempPath = System.IO.Path.GetTempPath();
            string SPPath   = Path.Combine(tempPath, "bimsyncSharedParameter.txt");

            if (!File.Exists(SPPath))
            {
                //extract the familly
                List <string> files = new List <string>();
                files.Add("bimsyncSharedParameter.txt");
                Services.ExtractEmbeddedResource(tempPath, "bimsync.Resources", files);
            }

            //set the shared param file
            app.SharedParametersFilename = SPPath;

            //Define a category set containing the project properties
            CategorySet myCategorySet   = app.Create.NewCategorySet();
            Categories  categories      = doc.Settings.Categories;
            Category    projectCategory = categories.get_Item(BuiltInCategory.OST_ProjectInformation);

            myCategorySet.Insert(projectCategory);

            //Retrive shared parameters
            DefinitionFile myDefinitionFile = app.OpenSharedParameterFile();

            DefinitionGroup definitionGroup = myDefinitionFile.Groups.get_Item("bimsync");

            foreach (Definition paramDef in definitionGroup.Definitions)
            {
                // Get the BingdingMap of current document.
                BindingMap bindingMap = doc.ParameterBindings;

                //the parameter does not exist
                if (!bindingMap.Contains(paramDef))
                {
                    //Create an instance of InstanceBinding
                    InstanceBinding instanceBinding = app.Create.NewInstanceBinding(myCategorySet);

                    bindingMap.Insert(paramDef, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                }
                //the parameter is not added to the correct categories
                else if (bindingMap.Contains(paramDef))
                {
                    InstanceBinding currentBinding = bindingMap.get_Item(paramDef) as InstanceBinding;
                    currentBinding.Categories = myCategorySet;
                    bindingMap.ReInsert(paramDef, currentBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                }
            }

            //Reset to the previous shared parameters text file
            app.SharedParametersFilename = previousSharedParam;
            File.Delete(SPPath);
        }
示例#7
0
        /// <summary>
        /// Add Shared GID Parameter to active Document
        /// </summary>
        /// <param name="document"></param>
        /// <returns>returns if operation succeeded</returns>
        public static bool GrevitAddSharedParameter(this Document document)
        {
            try
            {
                string parameterName = "GID";

                ParameterType parameterType = ParameterType.Text;

                string sharedParameterFile = document.Application.SharedParametersFilename;

                string tempSharedParameterFile = System.IO.Path.GetTempFileName() + ".txt";
                using (System.IO.File.Create(tempSharedParameterFile)) { }

                document.Application.SharedParametersFilename = tempSharedParameterFile;

                // Create a new Category Set to apply the parameter to
                CategorySet categories = document.Application.Create.NewCategorySet();

                // Walk thru all categories and add them if they allow bound parameters
                foreach (Category cat in document.Settings.Categories)
                {
                    if (cat.AllowsBoundParameters)
                    {
                        categories.Insert(cat);
                    }
                }

                // Create and External Definition in a Group called Grevit and a Parameter called GID
#if (!Revit2015)
                ExternalDefinition def = document.Application.OpenSharedParameterFile().Groups.Create("Grevit").Definitions.Create(new ExternalDefinitionCreationOptions(parameterName, parameterType)) as ExternalDefinition;
#else
                ExternalDefinition def = document.Application.OpenSharedParameterFile().Groups.Create("Grevit").Definitions.Create(new ExternalDefinitonCreationOptions(parameterName, parameterType)) as ExternalDefinition;
#endif

                document.Application.SharedParametersFilename = sharedParameterFile;
                System.IO.File.Delete(tempSharedParameterFile);

                // Apply the Binding to almost all Categories
                Autodesk.Revit.DB.Binding bin = document.Application.Create.NewInstanceBinding(categories);
                BindingMap map = (new UIApplication(document.Application)).ActiveUIDocument.Document.ParameterBindings;
                map.Insert(def, bin, BuiltInParameterGroup.PG_DATA);

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
示例#8
0
        internal void CreateBinding(string domain, string tempFile, Application app, Document doc, CategorySet catSet, StringBuilder sbFeedback)
        {
            //Parameter query

            var query = from pdef p in new pl().PL where string.Equals(p.Domain, domain) select p;

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

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

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

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#9
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();
            }
        }
示例#10
0
        private void Insert(Document doc, UIApplication uiapp, Definition visibleParamDef, BindingMap bindingMap)
        {
            CategorySet categorySet = uiapp.Application.Create.NewCategorySet();

            List <BuiltInCategory> listBuiltInCategory = new List <BuiltInCategory>()
            {
                BuiltInCategory.OST_PipeCurves,
                BuiltInCategory.OST_PipeFitting,
                BuiltInCategory.OST_PipeAccessory,
                BuiltInCategory.OST_PlumbingFixtures,
                BuiltInCategory.OST_MechanicalEquipment,
                BuiltInCategory.OST_PipeInsulations,
                BuiltInCategory.OST_FlexPipeCurves,
                BuiltInCategory.OST_DetailComponents
            };

            categorySet = Cat(doc, listBuiltInCategory, categorySet);
            InstanceBinding typeBinding = uiapp.Application.Create.NewInstanceBinding(categorySet);

            bindingMap.Insert(visibleParamDef, typeBinding, BuiltInParameterGroup.INVALID);
        }
示例#11
0
        private static void CreateProjectParam(Autodesk.Revit.ApplicationServices.Application app,
                                               string name, ParameterType type, bool visible, CategorySet catSet, BuiltInParameterGroup group, bool inst)
        {
            // Check whether the parameter has already been added.
            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;
            DefinitionBindingMapIterator itr = map.ForwardIterator();

            while (itr.MoveNext())
            {
                Definition exstDef = itr.Key;
                if (exstDef.Name == "LinkedTag")
                {
                    return;
                }
            }

            string orgFile  = app.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";

            using (File.Create(tempFile)) { }
            app.SharedParametersFilename = tempFile;

            ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create("TemporaryDefinitionGroup").Definitions.Create
                                         (new ExternalDefinitionCreationOptions(name, type)
            {
                Visible = visible
            }) as ExternalDefinition;

            app.SharedParametersFilename = orgFile;
            File.Delete(tempFile);

            Binding binding = app.Create.NewTypeBinding(catSet);

            if (inst)
            {
                binding = app.Create.NewInstanceBinding(catSet);
            }

            map.Insert(def, binding);
        }
示例#12
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);
        }
示例#13
0
        /// <summary>
        /// Method that finds the existing shared parameter and binds a new project parameter
        /// </summary>
        /// <param name="name"></param>
        /// <param name="cats"></param>
        /// <param name="group"></param>
        /// <param name="inst"></param>
        static public void CreateProjParamFromExistSharedParam(string name, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            try
            {
                DefinitionFile defFile = EADocumentData.App.OpenSharedParameterFile();
                if (defFile == null)
                {
                    throw new FileReadFailedException("No SharedParameter File!");
                }

                var v = (from DefinitionGroup dg in defFile.Groups
                         from ExternalDefinition d in dg.Definitions
                         where d.Name == name
                         select d);
                if (v == null || v.Count() < 1)
                {
                    throw new InvalidNameException("Invalid Name Input!");
                }

                ExternalDefinition def = v.First();

                Autodesk.Revit.DB.Binding binding = EADocumentData.App.Create.NewTypeBinding(cats);
                if (inst)
                {
                    binding = EADocumentData.App.Create.NewInstanceBinding(cats);
                }

                BindingMap map = (new UIApplication(EADocumentData.App)).ActiveUIDocument.Document.ParameterBindings;
                map.Insert(def, binding, group);
            }
            catch (InvalidNameException ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
            catch (FileReadFailedException ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
        }
示例#14
0
        public static void RawCreateProjectParameterFromNewSharedParameter(RvtApplication app, string defGroup, string name, ParameterType type, bool visible, CategorySet cats, BuiltInParameterGroup paramGroup, bool inst)
        {
            DefinitionFile defFile = app.OpenSharedParameterFile();

            if (defFile == null)
            {
                throw new Exception("No SharedParameter File!");
            }

            //ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create(defGroup).Definitions.Create(name, type, visible) as ExternalDefinition;
            ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create(defGroup).Definitions.Create(new ExternalDefinitionCreationOptions(name, type)) as ExternalDefinition;

            Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats);
            if (inst)
            {
                binding = app.Create.NewInstanceBinding(cats);
            }

            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;

            map.Insert(def, binding, paramGroup);
        }
示例#15
0
        public static Parameter AddParameterBase(Document doc, Element element, Category category, string parameterName, int parameterSetId, ForgeTypeId specId)
        {
            bool        isElementType = (element is ElementType);
            Definitions definitions   = isElementType ? Importer.TheCache.TypeGroupDefinitions : Importer.TheCache.InstanceGroupDefinitions;

            bool       newlyCreated = false;
            Definition definition   = definitions.get_Item(parameterName);

            if (definition == null)
            {
                ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(parameterName, specId);
                definition = definitions.Create(option);
                if (definition == null)
                {
                    Importer.TheLog.LogError(parameterSetId, "Couldn't create parameter: " + parameterName, false);
                    return(null);
                }
                newlyCreated = true;
            }

            Guid guid = (definition as ExternalDefinition).GUID;

            Parameter      parameter = null;
            ElementBinding binding   = null;
            bool           reinsert  = false;

            if (!newlyCreated)
            {
                BindingMap bindingMap = Importer.TheCache.GetParameterBinding(doc);
                binding  = bindingMap.get_Item(definition) as ElementBinding;
                reinsert = (binding != null);
            }

            if (binding == null)
            {
                if (isElementType)
                {
                    binding = new TypeBinding();
                }
                else
                {
                    binding = new InstanceBinding();
                }
            }

            // The binding can fail if we haven't identified a "bad" category above.  Use try/catch as a safety net.
            try
            {
                if (!reinsert || !binding.Categories.Contains(category))
                {
                    binding.Categories.Insert(category);

                    BindingMap bindingMap = Importer.TheCache.GetParameterBinding(doc);
                    if (reinsert)
                    {
                        bindingMap.ReInsert(definition, binding, BuiltInParameterGroup.PG_IFC);
                    }
                    else
                    {
                        bindingMap.Insert(definition, binding, BuiltInParameterGroup.PG_IFC);
                    }
                }

                parameter = element.get_Parameter(guid);
            }
            catch
            {
            }

            if (parameter == null)
            {
                Importer.TheLog.LogError(parameterSetId, "Couldn't create parameter: " + parameterName, false);
            }

            return(parameter);
        }
示例#16
0
        private bool AddParameter(Element element)
        {
            bool instanceBindOK = false;

            try
            {
                DefinitionFile  definitionFile = m_app.Application.OpenSharedParameterFile();
                DefinitionGroup defGroup       = definitionFile.Groups.get_Item("HOK BCF");
                if (null == defGroup)
                {
                    defGroup = definitionFile.Groups.Create("HOK BCF");
                }

                foreach (string defName in bcfParameters)
                {
#if RELEASE2015
                    Parameter parameter = element.LookupParameter(defName);
#else
                    Parameter parameter = element.get_Parameter(defName);
#endif
                    if (null != parameter)
                    {
                        continue;
                    }

                    Definition definition = defGroup.Definitions.get_Item(defName);
                    if (null == definition)
                    {
#if RELEASE2015
                        ExternalDefinitonCreationOptions option = new ExternalDefinitonCreationOptions(defName, ParameterType.Text);
                        definition = defGroup.Definitions.Create(option);
#else
                        definition = defGroup.Definitions.Create(defName, ParameterType.Text);
#endif
                    }

                    BindingMap      bindingMap      = m_app.ActiveUIDocument.Document.ParameterBindings;
                    InstanceBinding instanceBinding = bindingMap.get_Item(definition) as InstanceBinding;
                    if (null != instanceBinding)
                    {
                        instanceBinding.Categories.Insert(element.Category);
                        instanceBindOK = bindingMap.ReInsert(definition, instanceBinding);
                    }
                    else
                    {
                        CategorySet categories = m_app.Application.Create.NewCategorySet();
                        categories.Insert(element.Category);
                        instanceBinding = m_app.Application.Create.NewInstanceBinding(categories);
                        instanceBindOK  = bindingMap.Insert(definition, instanceBinding, BuiltInParameterGroup.PG_TEXT);
                    }
                    if (!instanceBindOK)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to add project parameters for element " + element.Name + "\n" + ex.Message, "CommandForm:AddParameter", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                instanceBindOK = false;
            }
            return(instanceBindOK);
        }
示例#17
0
        internal Result CreatePipelineBindings(UIApplication uiApp, ref string msg)
        {
            // UIApplication uiApp = commandData.Application;
            Document    doc = uiApp.ActiveUIDocument.Document;
            Application app = doc.Application;

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

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

            CategorySet catSet = ca.NewCategorySet();

            catSet.Insert(pipelineCat);

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

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

            StringBuilder sbFeedback = new StringBuilder();

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

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

            trans.Start();

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

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

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

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

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

            app.SharedParametersFilename = oriFile;

            return(Result.Succeeded);
        }
示例#18
0
        /// <summary>
        /// Creates a project parameter based on the definition of a shared parameter.
        /// </summary>
        /// <param name="parameterName">The name of the parameter.</param>
        /// <param name="instance">Set to true to create an instance parameter, false to create a type parameter.</param>
        /// <param name="categories">The categores to add this parameter to, by their built in parameter name.</param>
        /// <param name="parameterGroup">The parameter group for this parameter.</param>
        /// <returns></returns>
        public static bool BySharedParameter(string parameterName, bool instance, string[] categories, string parameterGroup = "PG_TEXT")
        {
            // Get current document
            Document doc = DocumentManager.Instance.CurrentDBDocument;

            // Get the BindingMap (contains all bindings)
            BindingMap     bm = doc.ParameterBindings;
            DefinitionFile df = doc.Application.OpenSharedParameterFile();

            /*
             * CATEGORES
             */
            // Create a CategorySet
            CategorySet myCategories = doc.Application.Create.NewCategorySet();

            foreach (string s in categories)
            {
                // Try to find the BuiltInCategory
                Autodesk.Revit.DB.BuiltInCategory tempCategory;
                if (!Enum.TryParse <Autodesk.Revit.DB.BuiltInCategory>(s, out tempCategory))
                {
                    throw new Exception(string.Format("BuiltInCategory {0} not found.", s));
                }

                // Add it to the CategorySet
                myCategories.Insert(doc.Settings.Categories.get_Item(tempCategory));
            }

            /*
             * PARAMETER GROUP
             */
            BuiltInParameterGroup pGroup;

            if (!System.Enum.TryParse <Autodesk.Revit.DB.BuiltInParameterGroup>(parameterGroup, out pGroup))
            {
                throw new Exception(string.Format("BuiltInParameterGroup {0} not found.", parameterGroup));
            }


            /*
             * CREATE THE BINDING
             */
            dynamic myBinding;

            // Create the InstanceBinding or the TypeBinding
            if (instance)
            {
                myBinding = doc.Application.Create.NewInstanceBinding(myCategories);
            }
            else
            {
                myBinding = doc.Application.Create.NewTypeBinding(myCategories);
            }

            // List to record outputs
            bool bindOk;

            // Ensure in transaction
            TransactionManager.Instance.EnsureInTransaction(doc);

            Definition def = FindDefinitionByName(parameterName, df);

            if (def == null)
            {
                throw new Exception(string.Format("Parameter definition for \"{0}\" not found.", parameterName));
            }
            else
            {
                bindOk = bm.Insert(def, myBinding, pGroup);
            }

            // Transaction done
            TransactionManager.Instance.TransactionTaskDone();

            return(bindOk);
        }
示例#19
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;
            BindingMap bindingMap = 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 (category == "" || binding == "" || browserGroup == "")
                {
                    emptyValueFlag = true;
                    break;
                }
            }

            if (!emptyValueFlag)
            {
                Transaction trans = new Transaction(myRevitDoc, "Insert Into Project 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();

                    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);
                    bindingMap      = myCommandData.Application.ActiveUIDocument.Document.ParameterBindings;

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

                    BuiltInParameterGroup paramGroup;

                    paramGroup = groupDict[browserGroup];

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

                trans.Commit();

                TaskDialog.Show("Insert into Project Parameters", "The Shared Parameters were inserted successfully");
                this.Close();
            }
            else
            {
                TaskDialog td = new TaskDialog("Insert into Project Parameters");
                td.MainInstruction = "Invalid value(s)";
                td.MainContent     = "Specify a value for Binding, Category, and Properties Group for each parameter before inserting into Project Parameters";
                td.Show();
            }
        }
示例#20
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);
            }
        }
示例#21
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            TaskDialog taskDialog = new TaskDialog("Shared Parameter Creator");

            taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconNone;
            taskDialog.MainInstruction = "Are you sure you want to create the Shared Parameters file?";
            taskDialog.CommonButtons   = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;

            fullFile_Excel = txtCSVFile.Text;

            insertIntoProjectParameters = chkInsert.Checked;

            if (fullFile_Excel == string.Empty)
            {
                TaskDialog.Show("No File Provided", "Make sure you have created a file with the .csv extension.");
            }
            else
            {
                if (taskDialog.Show() == TaskDialogResult.Yes)
                {
                    try
                    {
                        Category                  category        = null;
                        CategorySet               categorySet     = null;
                        InstanceBinding           instanceBinding = null;
                        Autodesk.Revit.DB.Binding typeBinding     = null;
                        BindingMap                bindingMap      = null;

                        categorySet     = myCommandData.Application.Application.Create.NewCategorySet();
                        instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                        typeBinding     = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                        bindingMap      = myCommandData.Application.ActiveUIDocument.Document.ParameterBindings;

                        DefinitionFile sharedParametersFile;

                        string fileName = string.Empty;
                        string filePath = string.Empty;

                        filePath = Path.GetDirectoryName(fullFile_Excel);
                        fileName = Path.GetFileNameWithoutExtension(fullFile_Excel);

                        fullFile_Parameters = filePath + "\\" + fileName + ".txt";

                        // THE SHARED PARAMETER FILE
                        sharedParametersFile = OpenSharedParametersFile(myCommandData.Application.Application);

                        DefinitionGroup sharedParameterDefinition = null;
                        Definition      definition = null;

                        string strTextLine = string.Empty;

                        StreamReader objReader = new System.IO.StreamReader(fullFile_Excel);
                        System.Collections.Specialized.StringCollection parameterCollection = new System.Collections.Specialized.StringCollection();

                        while (objReader.Peek() != -1)
                        {
                            strTextLine = objReader.ReadLine();

                            parameterCollection.Add(strTextLine);
                        }

                        //REVIT TRANSACTION
                        Transaction trans = new Transaction(myRevitDoc, "Create Shared Parameters");

                        trans.Start();

                        foreach (string param in parameterCollection)
                        {
                            // A, appliesTo, CATEGORY
                            // B, sharedParameterGroup, SHARED PARAMETER GROUP
                            // C, parameterDataType, DATA TYPE
                            // D, bindType, BINDING TYPE
                            // E, PARAMETER NAME

                            string        appliesTo            = string.Empty;
                            string        groupUnder           = string.Empty;
                            string        sharedParameterGroup = string.Empty;
                            ParameterType parameterDataType;
                            parameterDataType = ParameterType.Text;
                            string parameterDataType_Test = string.Empty;
                            string bindType      = string.Empty;
                            string parameterName = string.Empty;

                            char[]   chrSeparator = new char[] { ',' };
                            string[] arrValues    = param.Split(chrSeparator, StringSplitOptions.None);

                            appliesTo              = arrValues[0];
                            sharedParameterGroup   = arrValues[1];
                            parameterDataType_Test = arrValues[2];
                            bindType      = arrValues[3];
                            parameterName = arrValues[4];

                            switch (parameterDataType_Test)
                            {
                            case "Text":
                                parameterDataType = ParameterType.Text;
                                break;

                            case "Integer":
                                parameterDataType = ParameterType.Integer;
                                break;

                            case "Number":
                                parameterDataType = ParameterType.Number;
                                break;

                            case "Length":
                                parameterDataType = ParameterType.Length;
                                break;

                            case "Area":
                                parameterDataType = ParameterType.Area;
                                break;

                            case "Volume":
                                parameterDataType = ParameterType.Volume;
                                break;

                            case "Angle":
                                parameterDataType = ParameterType.Angle;
                                break;

                            case "Slope":
                                parameterDataType = ParameterType.Slope;
                                break;

                            case "Currency":
                                parameterDataType = ParameterType.Currency;
                                break;

                            case "Mass Density":
                                parameterDataType = ParameterType.MassDensity;
                                break;

                            case "URL":
                                parameterDataType = ParameterType.URL;
                                break;

                            case "Material":
                                parameterDataType = ParameterType.Material;
                                break;

                            case "Image":
                                parameterDataType = ParameterType.Image;
                                break;

                            case "Yes/No":
                                parameterDataType = ParameterType.YesNo;
                                break;

                            default:
                                parameterDataType = ParameterType.Text;
                                break;
                            }

                            sharedParameterDefinition = sharedParametersFile.Groups.get_Item(sharedParameterGroup);

                            if ((sharedParameterDefinition == null))
                            {
                                sharedParameterDefinition = sharedParametersFile.Groups.Create(sharedParameterGroup);
                            }

                            category    = myCommandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(appliesTo);
                            categorySet = myCommandData.Application.Application.Create.NewCategorySet();
                            categorySet.Insert(category);
                            instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                            typeBinding     = myCommandData.Application.Application.Create.NewTypeBinding(categorySet);

                            if ((parameterName != null))
                            {
                                definition = OpenDefinition(sharedParameterDefinition, parameterName, parameterDataType);
                            }

                            if (insertIntoProjectParameters)
                            {
                                if (bindType == "Type")
                                {
                                    bindingMap.Insert(definition, typeBinding, BuiltInParameterGroup.PG_DATA);
                                }
                                else
                                {
                                    bindingMap.Insert(definition, instanceBinding, BuiltInParameterGroup.PG_DATA);
                                }
                            }
                        }

                        //END REVIT TRANSACTION
                        trans.Commit();

                        objReader.Close();

                        TaskDialog.Show("File Created Sucessfully", "The Shared Parameter file was created successfully");
                    }
                    catch (Exception ex)
                    {
                        TaskDialog errorMessage = new TaskDialog("Create Shared Parameter Error");
                        errorMessage.MainInstruction = "An error occurrued while creating the Shared Parameter file." + "\n" + "Please read the following error message below";
                        errorMessage.MainContent     = ex.Message + Environment.NewLine + ex.Source;
                        errorMessage.Show();
                    }
                }
            }
        }
示例#22
0
        internal Result CreatePipelineBindings(UIApplication uiApp, ref string msg)
        {
            // UIApplication uiApp = commandData.Application;
            Document    doc = uiApp.ActiveUIDocument.Document;
            Application app = doc.Application;

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

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

            CategorySet catSet = ca.NewCategorySet();

            catSet.Insert(pipelineCat);

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

            StringBuilder sbFeedback = new StringBuilder();

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

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

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

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

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

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

            app.SharedParametersFilename = oriFile;

            return(Result.Succeeded);
        }