Пример #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
        public List <bool> SetNewParametersToInstances()
        {
            List <bool> instanceBindingOK = new List <bool>();

            if (SharedParameterFile != null && ActiveDefinitions != null)
            {
                CategorySet myCategories = App.Create.NewCategorySet();

                Category myCategory = UIApp.ActiveUIDocument.Document.Settings.Categories.get_Item(ActiveBuiltInCategory);

                myCategories.Insert(myCategory);

                InstanceBinding instanceBinding = App.Create.NewInstanceBinding(myCategories);

                BindingMap bindingMap = UIApp.ActiveUIDocument.Document.ParameterBindings;

                foreach (Definition definition in ActiveDefinitions)
                {
                    bool IsOk = bindingMap.Insert(definition, instanceBinding, BuiltInParameterGroup.PG_TEXT);
                    instanceBindingOK.Add(IsOk);
                }

                UIApp.ActiveUIDocument.SaveAs();
            }
            else
            {
                instanceBindingOK.Add(false);
            }
            return(instanceBindingOK);
        }
Пример #4
0
        public static bool CreateSharedProjectParameters(Document doc, string param, CategorySet catSet)
        {
            DefinitionFile sharedParamsFile = GetSharedParamsFile(doc);

            if (null == sharedParamsFile)
            {
                throw new Exception("Shared Paremeter file does not exist.\nSet or Create the project Shared Parameter file.");
            }

            DefinitionGroup sharedParamsGroup = GetCreateSharedParamsGroup(sharedParamsFile, "Group6Face");
            Definition      definition        = GetCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, param, true);

            BindingMap bindMap = doc.ParameterBindings;

            Autodesk.Revit.DB.Binding binding = bindMap.get_Item(definition);
            bindMap.ReInsert(definition, binding);

            InstanceBinding instanceBinding = doc.Application.Create.NewInstanceBinding(catSet);

            try
            {
                if (!doc.ParameterBindings.Insert(definition, instanceBinding))
                {
                    doc.ParameterBindings.ReInsert(definition, instanceBinding);
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception("Uneable to create parameter bindings.\n" + ex.Message);
            }
        }
Пример #5
0
        public void Add_SP_to_Cat()
        {
            //UIApplication uiapp = this.Application;
            UIDocument uidoc = this.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            //Application app = this.

            Category    cat = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls);
            CategorySet cs  = Application.Create.NewCategorySet();

            cs.Insert(cat);

            DefinitionFile deFile = Application.OpenSharedParameterFile();

            foreach (DefinitionGroup dg in deFile.Groups)
            {
                if (dg.Name == "New len")
                {
                    ExternalDefinition exDef = dg.Definitions.get_Item("CompanyName") as ExternalDefinition;
                    using (Transaction t = new Transaction(doc))
                    {
                        t.Start("Add Shared Parameters");
                        InstanceBinding newIB = Application.Create.NewInstanceBinding(cs);
                        doc.ParameterBindings.Insert(exDef, newIB, BuiltInParameterGroup.PG_TEXT);
                        t.Commit();
                    }
                }
            }
        }
Пример #6
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);
        }
Пример #7
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);
        }
Пример #8
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);
            }
        }
Пример #9
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);
        }
Пример #10
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);
            }
        }
        /// <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);
        }
Пример #12
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);
        }
Пример #13
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));
        }
Пример #14
0
        public void AddBindings(Document doc)
        {
            Binding binding;

            if (Instance)
            {
                binding = new InstanceBinding(GetCategories(doc));
            }
            else
            {
                binding = new TypeBinding(GetCategories(doc));
            }
            // assumes transaction open
            doc.ParameterBindings.Insert(Definition, binding, ParameterGroup);
        }
Пример #15
0
        public void CreateBuildingParameters(Document doc)
        {
            // Categories
            CategorySet catSet = new CategorySet();
            Category    cat    = Category.GetCategory(doc, BuiltInCategory.OST_GenericModel);

            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(buildingtypeParamName, ParameterType.Text);

            options.GUID        = new Guid(BuildingTypeParmGUID);
            options.Description = buildingtypeDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(streetNumberParamName, ParameterType.Text);
            options.GUID        = new Guid(StreetNumberParamGUID);
            options.Description = streetNumberDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(streetNameParamName, ParameterType.Text);
            options.GUID        = new Guid(StreetNameParamGUID);
            options.Description = streetNameDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(postalCodeParam, ParameterType.Text);
            options.GUID        = new Guid(PostalCodeParamGUID);
            options.Description = postalCodeParamDescription;
            CreateParam(doc, binding, defGroup, options);

            options             = new ExternalDefinitionCreationOptions(buldingHeightParam, ParameterType.Length);
            options.GUID        = new Guid(BuildingHeightParamGUID);
            options.Description = buildingHeightParamDescription;
            CreateParam(doc, binding, defGroup, options);
        }
        void f(Document doc)
        {
            Application app = doc.Application;

            DefinitionFile sharedParametersFile
                = app.OpenSharedParameterFile();

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

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

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

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

            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);
        }
Пример #17
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);
            }

            // 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));
        }
Пример #18
0
        public void CreateSharedParameters(Document doc, Application app, BuiltInCategory builtInCategory,
                                           string groupName, string ParameterName)
        {
            Category    Category    = doc.Settings.Categories.get_Item(builtInCategory);
            CategorySet categorySet = app.Create.NewCategorySet();

            categorySet.Insert(Category);

            string originalFile = app.SharedParametersFilename;
            string tempFile     = @"X:\Revit\Revit Support\SOM-Structural Parameters.txt";

            try
            {
                app.SharedParametersFilename = tempFile;

                DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();

                foreach (DefinitionGroup dg in sharedParameterFile.Groups)
                {
                    if (dg.Name == groupName)
                    {
                        ExternalDefinition externalDefinition = dg.Definitions.get_Item(ParameterName) as ExternalDefinition;

                        using (Transaction t = new Transaction(doc))
                        {
                            t.Start("Add Translation Shared Parameters");
                            //parameter binding
                            InstanceBinding newIB = app.Create.NewInstanceBinding(categorySet);
                            //parameter group to Identity Data in Revit Parameters
                            doc.ParameterBindings.Insert(externalDefinition, newIB, BuiltInParameterGroup.PG_IDENTITY_DATA);
                            doc.Regenerate();
                            t.Commit();
                        }
                    }
                }
            }
            catch { }
            finally
            {
                //reset to original file
                app.SharedParametersFilename = originalFile;
            }
        }
Пример #19
0
        public void CreateSampleSharedParameters(Document doc, Application app)
        {
            Category    category    = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls);
            CategorySet categorySet = app.Create.NewCategorySet();

            categorySet.Insert(category);

            string originalFile = app.SharedParametersFilename;

            //string tempFile = @"X:\Revit\Revit Support\SOM-Structural Parameters.txt";

            try
            {
                //app.SharedParametersFilename = tempFile;

                DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();

                foreach (DefinitionGroup dg in sharedParameterFile.Groups)
                {
                    if (dg.Name == "DYNAMO AND ADD-IN")
                    {
                        ExternalDefinition externalDefinition = dg.Definitions.get_Item("GROUP 1") as ExternalDefinition;

                        using (Transaction t = new Transaction(doc))
                        {
                            t.Start("Add Shared Parameters");
                            //parameter binding
                            InstanceBinding newIB = app.Create.NewInstanceBinding(categorySet);
                            //parameter group to text
                            doc.ParameterBindings.Insert(externalDefinition, newIB, BuiltInParameterGroup.PG_TEXT);
                            t.Commit();
                        }
                    }
                }
            }
            catch { }
            finally
            {
                //reset to original file
                app.SharedParametersFilename = originalFile;
            }
        }
Пример #20
0
        public void CreateSampleSharedParameters(Document doc, Application app)
        {
            Category    category    = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls);
            CategorySet categorySet = app.Create.NewCategorySet();

            categorySet.Insert(category);

            string originalFile = app.SharedParametersFilename;
            // for company standard shared parameter location
            string tempFile = @"C:\Users\FESG\Desktop\Soheila\BIM\C# programmming\Shared Parameters\New Parameters.txt";

            try
            {
                app.SharedParametersFilename = tempFile;

                DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();

                foreach (DefinitionGroup dg in sharedParameterFile.Groups)
                {
                    if (dg.Name == "My New Parameters")
                    {
                        ExternalDefinition externalDefinition = dg.Definitions.get_Item("GROUP 1") as ExternalDefinition;

                        using (Transaction t = new Transaction(doc))
                        {
                            t.Start("Add Shared Parameters");
                            //parameter binding
                            InstanceBinding newIB = app.Create.NewInstanceBinding(categorySet);
                            //parameter group to text
                            doc.ParameterBindings.Insert(externalDefinition, newIB, BuiltInParameterGroup.PG_TEXT);
                            t.Commit();
                        }
                    }
                }
            }
            catch { }
            finally
            {
                //reset to original file
                app.SharedParametersFilename = originalFile;
            }
        }
Пример #21
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);
        }
Пример #22
0
        public static List <RawProjectParameterInfo> RawGetProjectParametersInfo(Document doc)
        {
            RawProjectParameterInfo.FileName = doc.Title;
            List <RawProjectParameterInfo> paramList = new List <RawProjectParameterInfo>();

            BindingMap map = doc.ParameterBindings;
            DefinitionBindingMapIterator it = map.ForwardIterator();

            it.Reset();
            while (it.MoveNext())
            {
                ElementBinding  eleBinding = it.Current as ElementBinding;
                InstanceBinding insBinding = eleBinding as InstanceBinding;
                Definition      def        = it.Key;
                if (def != null)
                {
                    ExternalDefinition extDef = def as ExternalDefinition;
                    bool shared = extDef != null;
                    RawProjectParameterInfo param = new RawProjectParameterInfo
                    {
                        Name            = def.Name,
                        Group           = def.ParameterGroup,
                        Type            = def.ParameterType,
                        ReadOnly        = true, // def.IsReadOnly, def.IsReadOnly NOT working in either 2015 or 2014 but working in 2013
                        BoundToInstance = insBinding != null,
                        BoundCategories = RawConvertSetToList <Category>(eleBinding.Categories).Select(c => c.Name).ToArray(),

                        FromShared = shared,
                        GUID       = shared ? extDef.GUID.ToString() : string.Empty,
                        Owner      = shared ? extDef.OwnerGroup.Name : string.Empty,
                        Visible    = shared ? extDef.Visible : true,
                    };

                    paramList.Add(param);
                }
            }

            return(paramList);
        }
Пример #23
0
        Stream(ArrayList data, ElementBinding elemBind)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(ElementBinding)));

            data.Add(new Snoop.Data.Enumerable("Categories", elemBind.Categories));

            InstanceBinding instBind = elemBind as InstanceBinding;

            if (instBind != null)
            {
                Stream(data, instBind);
                return;
            }

            TypeBinding typeBind = elemBind as TypeBinding;

            if (typeBind != null)
            {
                Stream(data, typeBind);
                return;
            }
        }
Пример #24
0
        public void BindParameter(Document document, Definition definition, BuiltInCategory category)
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

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

            var app = document.Application;

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

                myCategories.Insert(myCategory);

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

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

                // Bind the definitions to the document
                //bool instanceBindOK = bindingMap.Insert(parameter, instanceBinding, group);
                //var test = RegisterParameter("Piling", "Easting", ParameterType.Length, false, "Easting");
                bool instanceBindOK = bindingMap.Insert(definition, instanceBinding);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Пример #25
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);
        }
Пример #26
0
        /// <summary>
        /// Method to retrieve filtered project parameters ID by category
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static string[] ProjectParameters(Document doc, string categoryName)
        {
            List <string> parametersID = new List <string>();

            BindingMap map = doc.ParameterBindings;
            DefinitionBindingMapIterator it = map.ForwardIterator();

            it.Reset();

            while (it.MoveNext())
            {
                ElementBinding  eleBinding = it.Current as ElementBinding;
                InstanceBinding insBinding = eleBinding as InstanceBinding;

                if (insBinding != null && IsInstBindingOfCategory(insBinding, categoryName))
                {
                    Definition def = it.Key;
                    if (def != null)
                    {
                        ExternalDefinition extDef = def as ExternalDefinition;

                        if (extDef != null)
                        {
                            string GUID = extDef.GUID.ToString();
                            parametersID.Add(GUID);
                        }
                        else
                        {
                            InternalDefinition intDef = def as InternalDefinition;
                            string             ID     = intDef.Id.ToString();
                            parametersID.Add(ID);
                        }
                    }
                }
            }
            return(parametersID.ToArray());
        }
Пример #27
0
        /// <summary>
        /// Method to check if Instance Binding is of a specific category
        /// </summary>
        /// <param name="insBinding"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static bool IsInstBindingOfCategory(InstanceBinding insBinding, string categoryName)
        {
            CategorySet         catSet   = insBinding.Categories;
            CategorySetIterator catSetIt = catSet.ForwardIterator();

            catSetIt.Reset();

            string cat = "";

            while (catSetIt.MoveNext())
            {
                Category category1 = catSetIt.Current as Category;
                cat = category1.Name;
            }

            if (cat != "" && cat == categoryName)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #28
0
        Stream(ArrayList data, InstanceBinding instBind)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(InstanceBinding)));

            // Nothing at this level yet!
        }
Пример #29
0
        /// <summary>
        /// 创建共享参数
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="app"></param>
        /// <returns></returns>
        public static bool ShareParameterGenerate(Document doc, Autodesk.Revit.ApplicationServices.Application app)
        {
            //设置共享参数
            string     TxtFileName = app.RecordingJournalFilename;
            Definition IdDf;
            Definition areaDf;
            Definition sizeDf;
            Definition XDf;
            Definition YDf;
            Definition ZDf;
            string     sNametmp = TxtFileName.Substring(0, TxtFileName.LastIndexOf("\\")) + "\\Teplate共享参数.txt";

            if (!File.Exists(sNametmp))
            {
                File.WriteAllText(sNametmp, "", Encoding.Default);
                app.SharedParametersFilename = sNametmp;
            }
            try
            {
                DefinitionFile  dsFile  = app.OpenSharedParameterFile();
                DefinitionGroup dsGroup = dsFile.Groups.ToList().Where(m => m.Name == "模板信息").First();
                IdDf   = dsGroup.Definitions.get_Item("HostElemID");
                areaDf = dsGroup.Definitions.get_Item("模板面积");
                sizeDf = dsGroup.Definitions.get_Item("模板尺寸");
                XDf    = dsGroup.Definitions.get_Item("X");
                YDf    = dsGroup.Definitions.get_Item("Y");
                ZDf    = dsGroup.Definitions.get_Item("Z");
            }
            catch
            {
                // 判断 路径是否有效,如果为空,读者可以创建一txt文件
                //将路径赋值给app.SharedParametersFilename
                DefinitionFile dfile = app.OpenSharedParameterFile();
                // 创建一个共享参数分组
                DefinitionGroup dg = dfile.Groups.Create("模板信息");

                // 参数创建的选项,包括参数名字,参数类型,用户是不是可以修改。。
                ExternalDefinitionCreationOptions elemID = new ExternalDefinitionCreationOptions("HostElemID", ParameterType.Integer);
                elemID.UserModifiable = false;
                ExternalDefinitionCreationOptions TemplateArea = new ExternalDefinitionCreationOptions("模板面积", ParameterType.Area);
                TemplateArea.UserModifiable = false;
                ExternalDefinitionCreationOptions TemplateSize = new ExternalDefinitionCreationOptions("模板尺寸", ParameterType.Text);
                TemplateSize.UserModifiable = false;
                ExternalDefinitionCreationOptions X = new ExternalDefinitionCreationOptions("X", ParameterType.Number);
                X.UserModifiable = false;
                ExternalDefinitionCreationOptions Y = new ExternalDefinitionCreationOptions("Y", ParameterType.Number);
                Y.UserModifiable = false;
                ExternalDefinitionCreationOptions Z = new ExternalDefinitionCreationOptions("Z", ParameterType.Number);
                Z.UserModifiable = false;

                // 创建参数
                IdDf   = dg.Definitions.Create(elemID);
                areaDf = dg.Definitions.Create(TemplateArea);
                sizeDf = dg.Definitions.Create(TemplateSize);
                XDf    = dg.Definitions.Create(X);
                YDf    = dg.Definitions.Create(Y);
                ZDf    = dg.Definitions.Create(Z);
            }
            if (IdDf == null || areaDf == null || YDf == null || XDf == null || ZDf == null || sizeDf == null)
            {
                return(false);
            }
            // 创建一个Category集合

            CategorySet cateSet = app.Create.NewCategorySet();

            // 获取墙的category
            Category TemplateCate = Category.GetCategory(doc, BuiltInCategory.OST_Parts);

            // 在Category集合中加入 模板的category
            bool flag = cateSet.Insert(TemplateCate);

            // 给 这个Category集合中的Category 创建一个实例绑定
            InstanceBinding TemBd = app.Create.NewInstanceBinding(cateSet);
            //ElementBinding TemBd = app.Create.NewTypeBinding(cateSet);

            // 获取当前Document的BindingMap
            BindingMap bmap = doc.ParameterBindings;

            //创建共享参数和Category之间的Binding
            bmap.Insert(IdDf, TemBd);
            bmap.Insert(areaDf, TemBd);
            bmap.Insert(sizeDf, TemBd);
            bmap.Insert(XDf, TemBd);
            bmap.Insert(YDf, TemBd);
            bmap.Insert(ZDf, TemBd);
            //设置视图,打开组成部分
            doc.ActiveView.PartsVisibility = PartsVisibility.ShowPartsOnly;
            Material partMat = null;

            try
            {
                partMat = FilterElementList <Material>(doc).Where(m => m.Name == "模板材质").First() as Material;
            }
            catch
            {
                partMat       = doc.GetElement(Material.Create(doc, "模板材质")) as Material;
                partMat.Color = new Color(255, 0, 0);
            }
            doc.Settings.Categories.get_Item(BuiltInCategory.OST_Parts).Material = partMat;
            return(true);
        }
Пример #30
0
 public void AddInstanceBinding(InstanceBinding binding)
 {
     this.InstanceBindings.Add(binding);
 }
        public static BindSharedParamResult BindSharedParam(
            Document doc,
            Category cat,
            string paramName,
            string grpName,
            ParameterType paramType,
            bool visible,
            bool instanceBinding)
        {
            try // generic
            {
                Application app = doc.Application;

                // This is needed already here to
                // store old ones for re-inserting

                CategorySet catSet = app.Create.NewCategorySet();

                // Loop all Binding Definitions
                // IMPORTANT NOTE: Categories.Size is ALWAYS 1 !?
                // For multiple categories, there is really one
                // pair per each category, even though the
                // Definitions are the same...

                DefinitionBindingMapIterator iter
                    = doc.ParameterBindings.ForwardIterator();

                while (iter.MoveNext())
                {
                    Definition     def = iter.Key;
                    ElementBinding elemBind
                        = (ElementBinding)iter.Current;

                    // Got param name match

                    if (paramName.Equals(def.Name,
                                         StringComparison.CurrentCultureIgnoreCase))
                    {
                        // Check for category match - Size is always 1!

                        if (elemBind.Categories.Contains(cat))
                        {
                            // Check Param Type

                            if (paramType != def.ParameterType)
                            {
                                return(BindSharedParamResult.eWrongParamType);
                            }

                            // Check Binding Type

                            if (instanceBinding)
                            {
                                if (elemBind.GetType() != typeof(InstanceBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }
                            else
                            {
                                if (elemBind.GetType() != typeof(TypeBinding))
                                {
                                    return(BindSharedParamResult.eWrongBindingType);
                                }
                            }

                            // Check Visibility - cannot (not exposed)
                            // If here, everything is fine,
                            // ie already defined correctly

                            return(BindSharedParamResult.eAlreadyBound);
                        }

                        // If here, no category match, hence must
                        // store "other" cats for re-inserting

                        else
                        {
                            foreach (Category catOld
                                     in elemBind.Categories)
                            {
                                catSet.Insert(catOld); // 1 only, but no index...
                            }
                        }
                    }
                }

                // If here, there is no Binding Definition for
                // it, so make sure Param defined and then bind it!

                DefinitionFile defFile
                    = GetOrCreateSharedParamsFile(app);

                DefinitionGroup defGrp
                    = GetOrCreateSharedParamsGroup(
                          defFile, grpName);

                Definition definition
                    = GetOrCreateSharedParamDefinition(
                          defGrp, paramType, paramName, visible);

                catSet.Insert(cat);

                InstanceBinding bind = null;

                if (instanceBinding)
                {
                    bind = app.Create.NewInstanceBinding(
                        catSet);
                }
                else
                {
                    bind = app.Create.NewTypeBinding(catSet);
                }

                // There is another strange API "feature".
                // If param has EVER been bound in a project
                // (in above iter pairs or even if not there
                // but once deleted), Insert always fails!?
                // Must use .ReInsert in that case.
                // See also similar findings on this topic in:
                // http://thebuildingcoder.typepad.com/blog/2009/09/adding-a-category-to-a-parameter-binding.html
                // - the code-idiom below may be more generic:

                if (doc.ParameterBindings.Insert(
                        definition, bind))
                {
                    return(BindSharedParamResult.eSuccessfullyBound);
                }
                else
                {
                    if (doc.ParameterBindings.ReInsert(
                            definition, bind))
                    {
                        return(BindSharedParamResult.eSuccessfullyBound);
                    }
                    else
                    {
                        return(BindSharedParamResult.eFailed);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(
                                    "Error in Binding Shared Param: {0}",
                                    ex.Message));

                return(BindSharedParamResult.eFailed);
            }
        }
        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;
        }
Пример #33
0
        private void Stream(ArrayList data, InstanceBinding instBind)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(InstanceBinding)));

                // Nothing at this level yet!
        }