/// <summary>
        /// Helper to get shared params definition.
        /// </summary>
        public static Definition GetOrCreateSharedParamsDefinition(
            DefinitionGroup defGroup,
            ParameterType defType,
            string defName,
            bool visible)
        {
            Definition definition
                = defGroup.Definitions.get_Item(
                      defName);

            if (null == definition)
            {
                try
                {
                    //definition = defGroup.Definitions.Create( defName, defType, visible ); // 2014

                    ExternalDefinitionCreationOptions opt
                        = new ExternalDefinitionCreationOptions(
                              defName, defType); // 2015

                    opt.Visible = visible;

                    definition = defGroup.Definitions.Create(opt); // 2015
                }
                catch (Exception)
                {
                    definition = null;
                }
            }
            return(definition);
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
0
        public static Definition sharedParameterYarat(RevitApplication app, string name, string group, ParameterType type, bool visible, Guid myGuid)
        {
            DefinitionFile defFile = myApp.OpenSharedParameterFile();

            if (defFile == null)
            {
                throw new Exception("No SharedParameter File!");
            }
            DefinitionGroup dg = RawConvertSetToList <DefinitionGroup>(defFile.Groups).FirstOrDefault(g => g.Name == group);

            if (dg == null)
            {
                dg = defFile.Groups.Create(group);
            }
            Definition def = RawConvertSetToList <Definition>(dg.Definitions).FirstOrDefault(d => d.Name == name);

            if (def != null)
            {
                return(def);
            }
            //Guid myGuid = new Guid("A0AD7058-9A98-47AC-89B1-0E1CBD5FCDCB");
            ExternalDefinitionCreationOptions edco = new ExternalDefinitionCreationOptions(name, type);

            edco.GUID    = myGuid;
            edco.Visible = true;
            def          = dg.Definitions.Create(edco);
            return(def);
        }
        public void AddParameterToGroup(string parameterName)
        {
            // add our parameter to the group

            ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(parameterName, ParameterType.Text);
            Definition def = SharedParameterDefinitionGroup.Definitions.Create(option);
        }
Ejemplo n.º 6
0
        private void addParameterToAreas()
        {
            try
            {
                CategorySet set  = new CategorySet();
                Category    area = CurrentDoc.Settings.Categories.get_Item(BuiltInCategory.OST_Areas);
                set.Insert(area);
                var binding = CurrentDoc.Application.Create.NewInstanceBinding(set);

                if (String.IsNullOrEmpty(CurrentDoc.Application.SharedParametersFilename) || (System.IO.File.Exists(CurrentDoc.Application.SharedParametersFilename) == false))
                {
                    // make our own file.
                    string file = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "RevitSharedParameters.txt");
                    CurrentDoc.Application.SharedParametersFilename = file;
                    System.IO.File.WriteAllText(file, "");
                }
                DefinitionFile defFile = CurrentDoc.Application.OpenSharedParameterFile();

                var group = defFile.Groups.get_Item("AreaRoomTypes");
                if (group == null)
                {
                    group = defFile.Groups.Create("AreaRoomTypes");
                }

                ExternalDefinitionCreationOptions opts = new ExternalDefinitionCreationOptions(TypeParam, ParameterType.Text);
                Definition def = group.Definitions.Create(opts);
                CurrentDoc.ParameterBindings.Insert(def, binding);
            }
            catch (Exception ex)
            {
                log("Tried to add the " + TypeParam + " parameter to Areas, but failed! " + ex.GetType().Name + ": " + ex.Message);
            }
        }
Ejemplo n.º 7
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);
            }
        }
Ejemplo n.º 8
0
        public static Definition GetOrCreateSharedParamsDefinition(
            DefinitionGroup defGroup,
            ForgeTypeId forgeTypeId,
            string defName,
            bool visible)
        {
            Definition definition = defGroup.Definitions.get_Item(defName);

            if (null == definition)
            {
                try
                {
                    //definition = defGroup.Definitions.Create(defName, defType, visible);

                    // 'Autodesk.Revit.DB.Definitions.Create(string, Autodesk.Revit.DB.ParameterType, bool)' is obsolete:
                    // 'This method is deprecated in Revit 2015. Use Create(Autodesk.Revit.DB.ExternalDefinitonCreationOptions) instead'

                    // Modified code for Revit 2015
                    // and fixed typo in class name in Revit 2016

                    ExternalDefinitionCreationOptions opt
                        = new ExternalDefinitionCreationOptions(
                              defName, forgeTypeId);
                    opt.Visible = true;
                    definition  = defGroup.Definitions.Create(opt);
                }
                catch (Exception)
                {
                    definition = null;
                }
            }
            return(definition);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Helper to get shared params definition.
        /// </summary>
        public static Definition GetOrCreateSharedParamsDefinition(
            DefinitionGroup defGroup,
            ParameterType defType,
            string defName,
            string tooltip,
            bool visible)
        {
            Definition definition
                = defGroup.Definitions.get_Item(
                      defName);

            if (null == definition)
            {
                try
                {
                    //definition = defGroup.Definitions.Create( defName, defType, visible ); // 2014

                    ExternalDefinitionCreationOptions opt
                        = new ExternalDefinitionCreationOptions(
                              defName, defType); // 2015

                    opt.Visible     = visible;
                    opt.Description = tooltip;
                    definition      = defGroup.Definitions.Create(opt); // 2015
                }
                catch (Exception)
                {
                    TaskDialog.Show("Parameter exists.", "Parameter already exist. No action taken.");
                    definition = null;
                }
            }
            return(definition);
        }
        public Definition Create(string group, ExternalDefinitionCreationOptions externalDefinitionCreationOptions)
        {
            if (definitionFile == null)
            {
                return(null);
            }

            DefinitionGroup definitionGroup = null;

            foreach (DefinitionGroup definitionGroup_Temp in definitionFile.Groups)
            {
                if (definitionGroup_Temp.Name == group)
                {
                    definitionGroup = definitionGroup_Temp;
                    break;
                }
            }

            if (definitionGroup == null)
            {
                definitionGroup = definitionFile.Groups.Create(group);
            }

            Definition definition = definitionGroup.Definitions.Create(externalDefinitionCreationOptions);

            return(definition);
        }
Ejemplo n.º 11
0
        public static void ExportParameters(Document doc, string path)
        {
            DefinitionFile existingDefFile = doc.Application.OpenSharedParameterFile();

            //
            doc.Application.SharedParametersFilename = path;
            DefinitionFile tempDefFile = doc.Application.OpenSharedParameterFile();

            // Manager the Exported group
            DefinitionGroup exported = null;

            var query = from dg in tempDefFile.Groups
                        where dg.Name.Equals(doc.PathName + "-Exported")
                        select dg;

            if (query.Count() == 0)
            {
                exported = tempDefFile.Groups.Create(doc.PathName + "-Exported");
            }
            else
            {
                exported = query.First();
            }

            // Iterate over the shared parameters in the document
            BindingMap bindingMap           = doc.ParameterBindings;
            DefinitionBindingMapIterator it =
                bindingMap.ForwardIterator();

            it.Reset();

            while (it.MoveNext())
            {
                InternalDefinition        definition  = it.Key as InternalDefinition;
                Autodesk.Revit.DB.Binding currBinding = bindingMap.get_Item(definition);

                // Corroborate that the current parameter has not been exported previously
                Definition existingDef = exported.Definitions
                                         .Where(d => (d.Name.Equals(definition.Name))).FirstOrDefault();
                if (existingDef != null)
                {
                    continue;
                }

                // unearth and assign the parameter's GUID
                SharedParameterElement sharedParamElem =
                    doc.GetElement(definition.Id) as SharedParameterElement;

                if (sharedParamElem == null)
                {
                    continue;
                }

                ExternalDefinitionCreationOptions options =
                    new ExternalDefinitionCreationOptions(definition.Name, definition.ParameterType);
                options.GUID = sharedParamElem.GuidValue;

                Definition createdDefinition = exported.Definitions.Create(options);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets definition by sharing parameter file path.
        /// </summary>
        /// <param name="group"></param>
        /// <param name="paramName"></param>
        /// <param name="canEdit"></param>
        /// <returns></returns>
        public static Definition GetDefinition(this DefinitionGroup group, string paramName, bool canEdit = false)
        {
            if (group == null)
            {
                throw new ArgumentNullException(nameof(group));
            }

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

            var definition = group.Definitions.get_Item(paramName);

            if (definition != null)
            {
                return(definition);
            }

            var opt = new ExternalDefinitionCreationOptions(paramName, ParameterType.Text)
            {
                UserModifiable = canEdit
            };

            return(group.Definitions.Create(opt));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Create a project parameter
        /// </summary>
        /// <param name="app"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="visible"></param>
        /// <param name="cats"></param>
        /// <param name="group"></param>
        /// <param name="inst"></param>
        public static void RawCreateProjectParameter(Autodesk.Revit.ApplicationServices.Application app, string name, ParameterType type, bool visible, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            string oriFile  = app.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";

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

            ExternalDefinitionCreationOptions externalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(name, type);

            ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions.Create(externalDefinitionCreationOptions) as ExternalDefinition;

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

            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);
        }
Ejemplo n.º 14
0
        public static ExternalDefinitionCreationOptions CreateOptions(this Param param)
        {
            ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions(param.Name, ParameterType.Text);

            switch (param.Type)
            {
            default:
            case ParamType.Text:
                options.Type = ParameterType.Text;
                break;

            case ParamType.Length:
                options.Type = ParameterType.Length;
                break;

            case ParamType.Bool:
                options.Type = ParameterType.YesNo;
                break;

            case ParamType.Int:
                options.Type = ParameterType.Integer;
                break;

            case ParamType.Material:
                options.Type = ParameterType.Material;
                break;

            case ParamType.Area:
                options.Type = ParameterType.Area;
                break;
            }
            options.GUID           = param.Guid;
            options.UserModifiable = param.UserModifiable;
            return(options);
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
        void ProblemAddingParameterBindingForCategory(
            Document doc)
        {
            Application app = doc.Application;

            if (null == _spellingErrorCorrector)
            {
                _spellingErrorCorrector
                    = new Util.SpellingErrorCorrector(app);
            }

            DefinitionFile sharedParametersFile
                = app.OpenSharedParameterFile();

            DefinitionGroup group = sharedParametersFile
                                    .Groups.Create("Reinforcement");

            //Definition def = group.Definitions.Create( // 2014
            //  "ReinforcementParameter", ParameterType.Text );

            ExternalDefinitionCreationOptions opt
                = new ExternalDefinitionCreationOptions(
                      "ReinforcementParameter", ParameterType.Text);

            Definition def = group.Definitions.Create(opt); // 2015

            // To handle both ExternalDefinitonCreationOptions
            // and ExternalDefinitionCreationOptions:

            def = _spellingErrorCorrector.NewDefinition(
                group.Definitions, "ReinforcementParameter",
                ParameterType.Text);

            List <BuiltInCategory> bics
                = new List <BuiltInCategory>();

            //bics.Add(BuiltInCategory.OST_AreaRein);
            //bics.Add(BuiltInCategory.OST_FabricAreas);
            //bics.Add(BuiltInCategory.OST_FabricReinforcement);
            //bics.Add(BuiltInCategory.OST_PathRein);
            //bics.Add(BuiltInCategory.OST_Rebar);

            bics.Add(BuiltInCategory
                     .OST_IOSRebarSystemSpanSymbolCtrl);

            CategorySet catset = new CategorySet();

            foreach (BuiltInCategory bic in bics)
            {
                catset.Insert(
                    doc.Settings.Categories.get_Item(bic));
            }

            InstanceBinding binding
                = app.Create.NewInstanceBinding(catset);

            doc.ParameterBindings.Insert(def, binding,
                                         BuiltInParameterGroup.PG_CONSTRUCTION);
        }
        public ExternalDefinitionCreationOptions GetCreationOptions()
        {
            ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions(Name, Type);

            options.UserModifiable = UserModifiable;
            options.Description    = Description;
            return(options);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Create shared parameter for Rooms category
        /// </summary>
        /// <returns>True, shared parameter exists; false, doesn't exist</returns>
        private bool CreateMyRoomSharedParameter()
        {
            // Create Room Shared Parameter Routine: -->
            // 1: Check whether the Room shared parameter("External Room ID") has been defined.
            // 2: Share parameter file locates under sample directory of this .dll module.
            // 3: Add a group named "SDKSampleRoomScheduleGroup".
            // 4: Add a shared parameter named "External Room ID" to "Rooms" category, which is visible.
            //    The "External Room ID" parameter will be used to map to spreadsheet based room ID(which is unique)

            try
            {
                // check whether shared parameter exists
                if (ShareParameterExists(RoomsData.SharedParam))
                {
                    return(true);
                }

                // create shared parameter file
                String modulePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                String paramFile  = modulePath + "\\RoomScheduleSharedParameters.txt";
                if (File.Exists(paramFile))
                {
                    File.Delete(paramFile);
                }
                FileStream fs = File.Create(paramFile);
                fs.Close();

                // cache application handle
                Autodesk.Revit.ApplicationServices.Application revitApp = m_commandData.Application.Application;

                // prepare shared parameter file
                m_commandData.Application.Application.SharedParametersFilename = paramFile;

                // open shared parameter file
                DefinitionFile parafile = revitApp.OpenSharedParameterFile();

                // create a group
                DefinitionGroup apiGroup = parafile.Groups.Create("SDKSampleRoomScheduleGroup");

                // create a visible "External Room ID" of text type.
                ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(RoomsData.SharedParam, ParameterType.Text);
                Definition roomSharedParamDef = apiGroup.Definitions.Create(ExternalDefinitionCreationOptions);

                // get Rooms category
                Category    roomCat    = m_commandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_Rooms);
                CategorySet categories = revitApp.Create.NewCategorySet();
                categories.Insert(roomCat);

                // insert the new parameter
                InstanceBinding binding = revitApp.Create.NewInstanceBinding(categories);
                m_commandData.Application.ActiveUIDocument.Document.ParameterBindings.Insert(roomSharedParamDef, binding);
                return(false);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to create shared parameter: " + ex.Message);
            }
        }
Ejemplo n.º 19
0
        public Definition RegisterParameter(Application application, ISharedParameter parameter)
        {
            if (application == null)
            {
                throw new ArgumentNullException(nameof(application));
            }

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

            Definition result;

            //TODO: Move to config file
            string path      = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\JPP Consulting\\Cedar\\SharedParameters.txt";
            string directory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\JPP Consulting\\Cedar";

            if (!File.Exists(path))
            {
                Directory.CreateDirectory(directory);
                FileStream fs = File.Create(path);
                fs.Close();
            }

            string currentPath = application.SharedParametersFilename;

            application.SharedParametersFilename = path;
            //Why does disposing the file throw an invalid exception?!?!?!?!?!?

            /*using (DefinitionFile defFile = _application.OpenSharedParameterFile())
             * {*/
            DefinitionFile  defFile     = application.OpenSharedParameterFile();
            DefinitionGroup pilingGroup = defFile.Groups.get_Item(parameter.GroupName);

            if (pilingGroup == null)
            {
                pilingGroup = defFile.Groups.Create(parameter.GroupName);
            }

            result = pilingGroup.Definitions.get_Item(parameter.Name);

            if (result == null)
            {
                ExternalDefinitionCreationOptions newDefinition = new ExternalDefinitionCreationOptions(parameter.Name, parameter.Type);
                newDefinition.UserModifiable = parameter.Editable;
                newDefinition.Description    = parameter.Description;
                newDefinition.GUID           = parameter.Id;
                result = pilingGroup.Definitions.Create(newDefinition);
            }

            application.SharedParametersFilename = currentPath;
            return(result);
            //}
        }
Ejemplo n.º 20
0
        private Definition CreateDefinition(DefinitionGroup defGroup, ExternalDefinitionCreationOptions options)
        {
            Definition definition = defGroup.Definitions.FirstOrDefault(d => d.Name == options.Name);

            if (definition == null)
            {
                definition = defGroup.Definitions.Create(options);
            }

            return(definition);
        }
Ejemplo n.º 21
0
        public void AddParameterToSPF(DefinitionGroup defG, string name, ParameterType type, bool visible)
        {
            ExternalDefinitionCreationOptions opt = new ExternalDefinitionCreationOptions(name, type)
            {
                Visible = visible
            };

            defG.Definitions.Create(opt);

            //Add parameter name to list
            ParametersAdded.Add(name);
        }
Ejemplo n.º 22
0
        private bool AddSharedTestParameter(ExternalCommandData commandData, string paramName, ParameterType paramType, bool userModifiable)
        {
            try
            {
                // check whether shared parameter exists
                if (ShareParameterExists(commandData.Application.ActiveUIDocument.Document, paramName))
                {
                    return(true);
                }

                // create shared parameter file
                String modulePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                String paramFile  = modulePath + "\\RebarTestParameters.txt";
                if (File.Exists(paramFile))
                {
                    File.Delete(paramFile);
                }
                FileStream fs = File.Create(paramFile);
                fs.Close();

                // cache application handle
                Autodesk.Revit.ApplicationServices.Application revitApp = commandData.Application.Application;

                // prepare shared parameter file
                commandData.Application.Application.SharedParametersFilename = paramFile;

                // open shared parameter file
                DefinitionFile parafile = revitApp.OpenSharedParameterFile();

                // create a group
                DefinitionGroup apiGroup = parafile.Groups.Create("RebarTestParamGroup");

                // create a visible param
                ExternalDefinitionCreationOptions ExtDefinitionCreationOptions = new ExternalDefinitionCreationOptions(paramName, paramType);
                ExtDefinitionCreationOptions.HideWhenNoValue = true;           //used this to show the parameter only in some rebar instances that will use it
                ExtDefinitionCreationOptions.UserModifiable  = userModifiable; //  set if users need to modify this
                Definition rebarSharedParamDef = apiGroup.Definitions.Create(ExtDefinitionCreationOptions);

                // get rebar category
                Category    rebarCat   = commandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_Rebar);
                CategorySet categories = revitApp.Create.NewCategorySet();
                categories.Insert(rebarCat);

                // insert the new parameter
                InstanceBinding binding = revitApp.Create.NewInstanceBinding(categories);
                commandData.Application.ActiveUIDocument.Document.ParameterBindings.Insert(rebarSharedParamDef, binding);
                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to create shared parameter: " + ex.Message);
            }
        }
Ejemplo n.º 23
0
        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();
                }
            }
        }
Ejemplo n.º 24
0
        public void CreateStreetParameters(Document doc)
        {
            // Categories
            CategorySet catSet = new CategorySet();
            Category    cat    = Category.GetCategory(doc, BuiltInCategory.OST_Roads);

            catSet.Insert(cat);

            Binding binding = new InstanceBinding(catSet);

            var app = doc.Application;

            app.SharedParametersFilename = ParamFile;
            DefinitionFile  defFile  = app.OpenSharedParameterFile();
            DefinitionGroup defGroup = defFile.Groups.FirstOrDefault(d => d.Name == defGroupName);

            if (defGroup == null)
            {
                defGroup = defFile.Groups.Create(defGroupName);
            }

            var options = new ExternalDefinitionCreationOptions(nameParamName, ParameterType.Text);

            options.GUID        = new Guid(NameParamGUID);
            options.Description = nameParamDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(streetUsageParamName, ParameterType.Text);
            options.GUID        = new Guid(StreetUsageParamGUID);
            options.Description = streetUsageDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(streetTypeParamName, ParameterType.Text);
            options.GUID        = new Guid(StreetTypeParamGUID);
            options.Description = streetTypeDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(streetLanesParam, ParameterType.Integer);
            options.GUID        = new Guid(StreetLanesParamGUID);
            options.Description = streetLanesDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(streetMaxSpeedParam, ParameterType.Integer);
            options.GUID        = new Guid(StreetMaxSpeedParamGUID);
            options.Description = streetMaxSpeedDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(streetSurfaceParam, ParameterType.Text);
            options.GUID        = new Guid(StreetSurfaceParamGUID);
            options.Description = streetSurfaceParamDescription;
            CreateParam(doc, binding, defGroup, options);
        }
        /// <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);
        }
Ejemplo n.º 26
0
        public Definition GetDefinition(DefinitionGroup group)
        {
            ExternalDefinitionCreationOptions externalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(this.Name, this.DataType);

            externalDefinitionCreationOptions.Visible = true;
            Definition definition = group.Definitions.get_Item(this.Name);

            if (definition == null)
            {
                definition = group.Definitions.Create(externalDefinitionCreationOptions);
            }
            return(definition);
        }
        /// <summary>
        /// Get a external definition if there exists one, otherwise create a new one.
        /// </summary>
        /// <param name="group">Definition group</param>
        /// <returns>External definition</returns>
        protected ExternalDefinition GetOrCreateDef(DefinitionGroup group)
        {
            ExternalDefinition Bdef =
                group.Definitions.get_Item(m_name) as ExternalDefinition;

            if (Bdef == null)
            {
                ExternalDefinitionCreationOptions ExternalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(m_name, SpecTypeId.ReinforcementLength);
                Bdef = group.
                       Definitions.Create(ExternalDefinitionCreationOptions) as ExternalDefinition;
            }

            return(Bdef);
        }
Ejemplo n.º 28
0
 public bool CreateUserDefinedParameter(ParameterInfo parameterInfo)
 {
     if (parameterInfo.ParameterIsProject)
     {
         return(false);
     }
     this.StartTransaction();
     try
     {
         DefinitionGroup sharedGroup = this.GetSharedGroup();
         Definition      definition  = sharedGroup.Definitions.get_Item(parameterInfo.ParameterName);
         if (definition == null)
         {
             ExternalDefinitionCreationOptions externalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(parameterInfo.ParameterName, parameterInfo.ParameterType);
             definition = sharedGroup.Definitions.Create(externalDefinitionCreationOptions);
             Log.WriteLine("Create shared parameter: " + parameterInfo.ParameterName);
         }
         ElementBinding elementBinding;
         if (parameterInfo.ParameterForType)
         {
             elementBinding = this.m_revitApp.Create.NewTypeBinding(parameterInfo.Categories);
             Log.WriteLine("Binding with types");
         }
         else
         {
             elementBinding = this.m_revitApp.Create.NewInstanceBinding(parameterInfo.Categories);
             Log.WriteLine("Binding with instances");
         }
         bool flag = this.m_revitDoc.ParameterBindings.Insert(definition, elementBinding, parameterInfo.ParameterGroup);
         Log.WriteLine("Submit binding");
         bool result;
         if (!flag)
         {
             this.RollbackTransaction();
             result = false;
             return(result);
         }
         this.CommitTransaction();
         result = true;
         return(result);
     }
     catch (System.Exception ex)
     {
         Log.WriteLine("Create shared parameter failed");
         Log.WriteLine(ex.ToString());
         this.RollbackTransaction();
     }
     return(false);
 }
Ejemplo n.º 29
0
        AddSharedParamsToFile()
        {
            // open the file
            DefinitionFile sharedParametersFile = null;

            try
            {
                sharedParametersFile = OpenSharedParamFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Can't open Shared Parameters file. (Exception: {0})", ex.Message));
                return;
            }

            // get or create our group
            DefinitionGroup sharedParameterGroup = sharedParametersFile.Groups.get_Item(m_paramGroupName);

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

            // get or create the parameter
            Definition sharedParameterDefinition = sharedParameterGroup.Definitions.get_Item(m_paramName);

            if (sharedParameterDefinition == null)
            {
                //sharedParameterDefinition = sharedParameterGroup.Definitions.Create( m_paramName, ParameterType.Text, true ); // 2015, jeremy: 'Autodesk.Revit.DB.Definitions.Create(string, Autodesk.Revit.DB.ParameterType, bool)' is obsolete: 'This method is deprecated in Revit 2015. Use Create(Autodesk.Revit.DB.ExternalDefinitonCreationOptions) instead'
                ExternalDefinitionCreationOptions opt = new ExternalDefinitionCreationOptions(m_paramName, ParameterType.Text);
                opt.UserModifiable        = true;
                opt.Visible               = true;
                sharedParameterDefinition = sharedParameterGroup.Definitions.Create(opt); // 2016, jeremy
            }

            // create a category set with the wall category in it
            CategorySet categories   = m_app.Application.Create.NewCategorySet();
            Category    wallCategory = m_app.ActiveUIDocument.Document.Settings.Categories.get_Item("Walls");

            categories.Insert(wallCategory);

            // create a new instance binding for the wall categories
            InstanceBinding instanceBinding = m_app.Application.Create.NewInstanceBinding(categories);

            // add the binding
            m_app.ActiveUIDocument.Document.ParameterBindings.Insert(sharedParameterDefinition, instanceBinding);

            MessageBox.Show(string.Format("Added a shared parameter \"{0}\" that applies to Category \"Walls\".", m_paramName));
        }
Ejemplo n.º 30
0
        private bool CreateSharedParameter(string paramName, ParameterType paramType, BuiltInParameterGroup pramGroup)
        {
            var created = false;

            using (var trans = new Transaction(m_doc))
            {
                try
                {
                    var definitionFile = m_app.Application.OpenSharedParameterFile();
                    if (null != definitionFile)
                    {
                        trans.Start("Create a shared parameter");
                        var groups = definitionFile.Groups;
                        var group  = groups.get_Item("HOK Tools");
                        if (null == group)
                        {
                            group = groups.Create("HOK Tools");
                        }
                        var definition = group.Definitions.get_Item(paramName);
                        if (definition == null)
                        {
#if RELEASE2015
                            definition = group.Definitions.Create(paramName, paramType);
#else
                            var options = new ExternalDefinitionCreationOptions(paramName, paramType);
                            definition = group.Definitions.Create(options);
#endif
                        }

                        var categorySet  = m_app.Application.Create.NewCategorySet();
                        var roomCategory = m_doc.Settings.Categories.get_Item(BuiltInCategory.OST_Rooms);
                        categorySet.Insert(roomCategory);

                        var instanceBinding = m_app.Application.Create.NewInstanceBinding(categorySet);
                        var bindingMap      = m_doc.ParameterBindings;
                        var instanceBindOK  = bindingMap.Insert(definition, instanceBinding, pramGroup);
                        trans.Commit();
                        created = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not create the Ceiling Height parametert." + paramName + "\n" + ex.Message, "CeilingHeightUtil : CreateSharedParameter", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    trans.RollBack();
                    created = false;
                }
            }
            return(created);
        }
Ejemplo n.º 31
0
      AddSharedParamsToFile()
      {

         // open the file
         DefinitionFile sharedParametersFile = null;
         try
         {
            sharedParametersFile = OpenSharedParamFile();
         }
         catch (Exception ex)
         {
            MessageBox.Show(string.Format("Can't open Shared Parameters file. (Exception: {0})", ex.Message));
            return;
         }

         // get or create our group
         DefinitionGroup sharedParameterGroup = sharedParametersFile.Groups.get_Item(m_paramGroupName);
         if (sharedParameterGroup == null)
         {
            sharedParameterGroup = sharedParametersFile.Groups.Create(m_paramGroupName);
         }

         // get or create the parameter
         Definition sharedParameterDefinition = sharedParameterGroup.Definitions.get_Item(m_paramName);
         if (sharedParameterDefinition == null)
         {
           //sharedParameterDefinition = sharedParameterGroup.Definitions.Create( m_paramName, ParameterType.Text, true ); // 2015, jeremy: 'Autodesk.Revit.DB.Definitions.Create(string, Autodesk.Revit.DB.ParameterType, bool)' is obsolete: 'This method is deprecated in Revit 2015. Use Create(Autodesk.Revit.DB.ExternalDefinitonCreationOptions) instead'
           ExternalDefinitionCreationOptions opt = new ExternalDefinitionCreationOptions( m_paramName, ParameterType.Text );
           opt.Visible = true;
           sharedParameterDefinition = sharedParameterGroup.Definitions.Create( opt ); // 2016, jeremy

         }

         // create a category set with the wall category in it
         CategorySet categories = m_app.Application.Create.NewCategorySet();
         Category wallCategory = m_app.ActiveUIDocument.Document.Settings.Categories.get_Item("Walls");
         categories.Insert(wallCategory);

         // create a new instance binding for the wall categories
         InstanceBinding instanceBinding = m_app.Application.Create.NewInstanceBinding(categories);

         // add the binding
         m_app.ActiveUIDocument.Document.ParameterBindings.Insert(sharedParameterDefinition, instanceBinding);

         MessageBox.Show(string.Format("Added a shared parameter \"{0}\" that applies to Category \"Walls\".", m_paramName));
      }
        // Previous tests:
        //
        // We also test using BuiltInCategory.OST_Walls to
        // demonstrate that the same technique works with system
        // families just as well as with standard ones.
        //
        // To test attaching shared parameters to inserted
        // DWG files, which generate their own category on
        // the fly, we also identify the category by
        // category name.
        //
        // The last test is for attaching shared parameters
        // to model groups.
        //
        //static public BuiltInCategory Target = BuiltInCategory.OST_Walls;
        //static public string Target = "Drawing1.dwg";
        //static public BuiltInCategory Target = BuiltInCategory.OST_IOSModelGroups; // doc.Settings.Categories.get_Item returns null
        //static public string Target = "Model Groups"; // doc.Settings.Categories.get_Item throws an exception SystemInvalidOperationException "Operation is not valid due to the current state of the object."
        //static public BuiltInCategory Target = BuiltInCategory.OST_Lines; // model lines
        //static public BuiltInCategory Target = BuiltInCategory.OST_SWallRectOpening; // Rectangular Straight Wall Openings, case 1260656 [Add Parameters Wall Opening]
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              Application app = uiapp.Application;
              Document doc = uiapp.ActiveUIDocument.Document;
              Category cat = null;

              // The category to define the parameter for.

              #region Determine model group category
            #if DETERMINE_MODEL_GROUP_CATEGORY
              List<Element> modelGroups = new List<Element>();
              //Filter fType = app.Create.Filter.NewTypeFilter( typeof( Group ) ); // "Binding the parameter to the category Model Groups is not allowed"
              Filter fType = app.Create.Filter.NewTypeFilter( typeof( GroupType ) ); // same result "Binding the parameter to the category Model Groups is not allowed"
              Filter fCategory = app.Create.Filter.NewCategoryFilter( BuiltInCategory.OST_IOSModelGroups );
              Filter f = app.Create.Filter.NewLogicAndFilter( fType, fCategory );
              if ( 0 < doc.get_Elements( f, modelGroups ) )
              {
            cat = modelGroups[0].Category;
              }
            #endif // DETERMINE_MODEL_GROUP_CATEGORY
              #endregion // Determine model group category

              if( null == cat )
              {
            cat = doc.Settings.Categories.get_Item( Target );
              }

              // Retrieve shared parameter definition file.

              DefinitionFile sharedParamsFile = Util
            .GetSharedParamsFile( app );

              if( null == sharedParamsFile )
              {
            message = "Error getting the shared params file.";
            return Result.Failed;
              }

              // Get or create the shared parameter group.

              DefinitionGroup sharedParamsGroup
            = sharedParamsFile.Groups.get_Item(
              Util.SharedParameterGroupName );

              if( null == sharedParamsGroup )
              {
            sharedParamsGroup = sharedParamsFile.Groups
              .Create( Util.SharedParameterGroupName );
              }

              // Visibility of the new parameter: the
              // Category.AllowsBoundParameters property
              // determines whether a category is allowed to
              // have user-visible shared or project parameters.
              // If it is false, it may not be bound to visible
              // shared parameters using the BindingMap. Note
              // that non-user-visible parameters can still be
              // bound to these categories. In our case, we
              // make the shared parameter user visible, if
              // the category allows it.

              bool visible = cat.AllowsBoundParameters;

              // Get or create the shared parameter definition.

              Definition def = sharedParamsGroup.Definitions
            .get_Item( Util.SharedParameterName );

              if( null == def )
              {
            ExternalDefinitionCreationOptions opt
              = new ExternalDefinitionCreationOptions(
            Util.SharedParameterName,
            ParameterType.Number );

            opt.Visible = visible;

            def = sharedParamsGroup.Definitions.Create(
              opt );
              }

              if( null == def )
              {
            message = "Error creating shared parameter.";
            return Result.Failed;
              }

              // Create the category set for binding and
              // add the category of interest to it.

              CategorySet catSet = app.Create.NewCategorySet();

              catSet.Insert( cat );

              // Bind the parameter.

              using( Transaction t = new Transaction( doc ) )
              {
            t.Start( "Bind FireRating Shared Parameter" );

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

            // We could check if it is already bound; if so,
            // Insert will apparently just ignore it.

            doc.ParameterBindings.Insert( def, binding );

            // You can also specify the parameter group here:

            //doc.ParameterBindings.Insert( def, binding,
            //  BuiltInParameterGroup.PG_GEOMETRY );

            t.Commit();
              }
              return Result.Succeeded;
        }
        /// <summary>
        /// Create a new shared parameter
        /// </summary>
        /// <param name="doc">Document</param>
        /// <param name="cat">Category to bind the parameter definition</param>
        /// <param name="nameSuffix">Parameter name suffix</param>
        /// <param name="typeParameter">Create a type parameter? If not, it is an instance parameter.</param>
        /// <returns></returns>
        bool CreateSharedParameter(
            Document doc,
            Category cat,
            int nameSuffix,
            bool typeParameter)
        {
            Application app = doc.Application;

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

              // get or set the current shared params filename:

              string filename
            = app.SharedParametersFilename;

              if( 0 == filename.Length )
              {
            string path = _filename;
            StreamWriter stream;
            stream = new StreamWriter( path );
            stream.Close();
            app.SharedParametersFilename = path;
            filename = app.SharedParametersFilename;
              }

              // get the current shared params file object:

              DefinitionFile file
            = app.OpenSharedParameterFile();

              if( null == file )
              {
            Util.ErrorMsg(
              "Error getting the shared params file." );

            return false;
              }

              // get or create the shared params group:

              DefinitionGroup group
            = file.Groups.get_Item( _groupname );

              if( null == group )
              {
            group = file.Groups.Create( _groupname );
              }

              if( null == group )
              {
            Util.ErrorMsg(
              "Error getting the shared params group." );

            return false;
              }

              // set visibility of the new parameter:

              // Category.AllowsBoundParameters property
              // indicates if a category can have user-visible
              // shared or project parameters. If it is false,
              // it may not be bound to visible shared params
              // using the BindingMap. Please note that
              // non-user-visible parameters can still be
              // bound to these categories.

              bool visible = cat.AllowsBoundParameters;

              // get or create the shared params definition:

              string defname = _defname + nameSuffix.ToString();

              Definition definition = group.Definitions.get_Item(
            defname );

              if( null == definition )
              {
            //definition = group.Definitions.Create( defname, _deftype, visible ); // 2014

            ExternalDefinitionCreationOptions opt
              = new ExternalDefinitionCreationOptions(
            defname, _deftype );

            opt.Visible = visible;

            definition = group.Definitions.Create( opt ); // 2015
              }
              if( null == definition )
              {
            Util.ErrorMsg(
              "Error creating shared parameter." );

            return false;
              }

              // create the category set containing our category for binding:

              CategorySet catSet = ca.NewCategorySet();
              catSet.Insert( cat );

              // bind the param:

              try
              {
            Binding binding = typeParameter
              ? ca.NewTypeBinding( catSet ) as Binding
              : ca.NewInstanceBinding( catSet ) as Binding;

            // we could check if it is already bound,
            // but it looks like insert will just ignore
            // it in that case:

            doc.ParameterBindings.Insert( definition, binding );

            // we can also specify the parameter group here:

            //doc.ParameterBindings.Insert( definition, binding,
            //  BuiltInParameterGroup.PG_GEOMETRY );

            Debug.Print(
              "Created a shared {0} parameter '{1}' for the {2} category.",
              ( typeParameter ? "type" : "instance" ),
              defname, cat.Name );
              }
              catch( Exception ex )
              {
            Util.ErrorMsg( string.Format(
              "Error binding shared parameter to category {0}: {1}",
              cat.Name, ex.Message ) );
            return false;
              }
              return true;
        }
    public static Definition GetOrCreateSharedParamsDefinition(
      DefinitionGroup defGroup,
      ParameterType defType,
      string defName,
      bool visible)
    {
      Definition definition = defGroup.Definitions.get_Item(defName);
      if (null == definition)
      {
        try
        {
          //definition = defGroup.Definitions.Create(defName, defType, visible);

          // 'Autodesk.Revit.DB.Definitions.Create(string, Autodesk.Revit.DB.ParameterType, bool)' is obsolete: 
          // 'This method is deprecated in Revit 2015. Use Create(Autodesk.Revit.DB.ExternalDefinitonCreationOptions) instead'

          // Modified code for Revit 2015
          // and fixed typo in class name in Revit 2016

          ExternalDefinitionCreationOptions opt
            = new ExternalDefinitionCreationOptions(
              defName, defType);
          opt.Visible = true;
          definition = defGroup.Definitions.Create(opt);
        }
        catch (Exception)
        {
          definition = null;
        }
      }
      return definition;
    }
        /// <summary>
        /// create project parameter
        /// source :http://spiderinnet.typepad.com/blog/2011/05/parameter-of-revit-api-31-create-project-parameter.html
        /// </summary>
        /// <param name="app">revit application</param>
        /// <param name="name">revit ui application</param>
        /// <param name="type">parameter type</param>
        /// <param name="cats">category set</param>
        /// <param name="group">parameter group</param>
        /// <param name="inst">is instance variable</param>
        public  void CreateProjectParameter(Application app, string name, ParameterType type,  CategorySet cats, BuiltInParameterGroup group, bool instance)
        {
    

            string oriFile = app.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";
            using (File.Create(tempFile)) { }
            app.SharedParametersFilename = tempFile;
    
             ExternalDefinitionCreationOptions edc=new ExternalDefinitionCreationOptions(name, type);
             ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions.Create(edc) as ExternalDefinition;

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

            Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats);
            if (instance) binding = app.Create.NewInstanceBinding(cats);
            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;
            map.Insert(def, binding, group);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Helper to get shared params definition.
        /// </summary>
        public static Definition GetOrCreateSharedParamsDefinition(
            DefinitionGroup defGroup,
            ParameterType defType,
            string defName,
            bool visible)
        {
            Definition definition
            = defGroup.Definitions.get_Item(
              defName );

              if( null == definition )
              {
            try
            {
              //definition = defGroup.Definitions.Create( defName, defType, visible ); // 2014

              ExternalDefinitionCreationOptions opt
            = new ExternalDefinitionCreationOptions(
              defName, defType ); // 2015

              opt.Visible = visible;

              definition = defGroup.Definitions.Create( opt ); // 2015
            }
            catch( Exception )
            {
              definition = null;
            }
              }
              return definition;
        }
        private static Parameter AddParameterBase(Document doc, Element element, string parameterName, int parameterSetId, ParameterType parameterType)
        {
            Category category = element.Category;
            if (category == null)
            {
                Importer.TheLog.LogWarning(parameterSetId, "Can't add parameters for element with no category.", true);
                return null;
            }
            else if (IsDisallowedCategory(category))
            {
                Importer.TheLog.LogWarning(parameterSetId, "Can't add parameters for category: " + category.Name, true);
                return null;
            }

            Guid guid;
            bool isElementType = (element is ElementType);
            DefinitionGroup definitionGroup = isElementType ? Importer.TheCache.DefinitionTypeGroup : Importer.TheCache.DefinitionInstanceGroup;

            KeyValuePair<string, bool> parameterKey = new KeyValuePair<string, bool>(parameterName, isElementType);

            bool newlyCreated = false;
            Definition definition = definitionGroup.Definitions.get_Item(parameterName);
            if (definition == null)
            {
               ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(parameterName, parameterType);
               definition = definitionGroup.Definitions.Create(option);
               newlyCreated = true;
            }
            guid = (definition as ExternalDefinition).GUID;

            Parameter parameter = null;
            if (definition != null)
            {
                ElementBinding binding = null;
                bool reinsert = false;
                bool changed = false;

                if (!newlyCreated)
                {
                    binding = doc.ParameterBindings.get_Item(definition) as ElementBinding;
                    reinsert = (binding != null);
                }

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

                if (category != null)
                {
                    if (category.Parent != null)
                        category = category.Parent;

                    if (!reinsert || !binding.Categories.Contains(category))
                    {
                        changed = true;
                        binding.Categories.Insert(category);
                    }

                    // The binding can fail if we haven't identified a "bad" category above.  Use try/catch as a safety net.
                    try
                    {
                        if (changed)
                        {
                            if (reinsert)
                                doc.ParameterBindings.ReInsert(definition, binding, BuiltInParameterGroup.PG_IFC);
                            else
                                doc.ParameterBindings.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;
        }
        void ProblemAddingParameterBindingForCategory(
            Document doc)
        {
            Application app = doc.Application;

              if( null == _spellingErrorCorrector )
              {
            _spellingErrorCorrector
              = new Util.SpellingErrorCorrector( app );
              }

              DefinitionFile sharedParametersFile
            = app.OpenSharedParameterFile();

              DefinitionGroup group = sharedParametersFile
            .Groups.Create( "Reinforcement" );

              //Definition def = group.Definitions.Create( // 2014
              //  "ReinforcementParameter", ParameterType.Text );

              ExternalDefinitionCreationOptions opt
            = new ExternalDefinitionCreationOptions(
              "ReinforcementParameter", ParameterType.Text );

              Definition def = group.Definitions.Create( opt ); // 2015

              // To handle both ExternalDefinitonCreationOptions
              // and ExternalDefinitionCreationOptions:

              def = _spellingErrorCorrector.NewDefinition(
            group.Definitions, "ReinforcementParameter",
            ParameterType.Text );

              List<BuiltInCategory> bics
            = new List<BuiltInCategory>();

              //bics.Add(BuiltInCategory.OST_AreaRein);
              //bics.Add(BuiltInCategory.OST_FabricAreas);
              //bics.Add(BuiltInCategory.OST_FabricReinforcement);
              //bics.Add(BuiltInCategory.OST_PathRein);
              //bics.Add(BuiltInCategory.OST_Rebar);

              bics.Add( BuiltInCategory
            .OST_IOSRebarSystemSpanSymbolCtrl );

              CategorySet catset = new CategorySet();

              foreach( BuiltInCategory bic in bics )
              {
            catset.Insert(
              doc.Settings.Categories.get_Item( bic ) );
              }

              InstanceBinding binding
            = app.Create.NewInstanceBinding( catset );

              doc.ParameterBindings.Insert( def, binding,
            BuiltInParameterGroup.PG_CONSTRUCTION );
        }