Ejemplo n.º 1
0
 //set current sp file to project
 private DefinitionFile SetAndOpenExternalSharedParamFile(Autodesk.Revit.ApplicationServices.Application application, string sharedParameterFile)
 {
     // set the path of shared parameter file to current Revit
     application.SharedParametersFilename = sharedParameterFile;
     // open the file
     return(application.OpenSharedParameterFile());
 }
        public void Execute(UIApplication _uiapp)
        {
            Transaction trans = new Transaction(doc, "Добавить параметры в семейства");

            trans.Start();
            foreach (var param in _params)
            {
                try
                {
                    DefinitionFile     sharedParameterFile = app.OpenSharedParameterFile();
                    var                RETRT = sharedParameterFile.Groups.FirstOrDefault(x => x.Name == param.GroupName);
                    ExternalDefinition externalDefinition = sharedParameterFile.Groups.FirstOrDefault(x => x.Name == param.GroupName).Definitions.get_Item(param.Name) as ExternalDefinition;
                    if (externalDefinition != null)
                    {
                        var dfhdnjfj = _paramsName.FirstOrDefault(x => x.Value == param.CurrentItem).Key;
                        var dgfdg    = _paramsGroup.FirstOrDefault(x => x.ToString() == dfhdnjfj);
                        doc.FamilyManager.AddParameter(externalDefinition, dgfdg, param.IsExusting);
                    }
                }
                catch
                {
                }
            }
            trans.Commit();
            MessageBox.Show("Параметры успешно загруженны", "Статус");
        }
Ejemplo n.º 3
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.º 4
0
        public static void RawCreateProjectParameterFromExistingSharedParameter(RvtApplication app, string name, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            DefinitionFile defFile = app.OpenSharedParameterFile();

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

            var v = (from DefinitionGroup dg in defFile.Groups
                     from ExternalDefinition d in dg.Definitions
                     where d.Name == name
                     select d);

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

            ExternalDefinition def = v.First();

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

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

            map.Insert(def, binding, group);
        }
        public void New(string path)
        {
            definitionFile = null;

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            File.WriteAllText(path, string.Empty);

            if (application != null)
            {
                application.SharedParametersFilename = path;
                definitionFile = application.OpenSharedParameterFile();
            }
        }
Ejemplo n.º 6
0
        private DefinitionFile OpenSharedParametersFile(Autodesk.Revit.ApplicationServices.Application application)
        {
            Autodesk.Revit.DB.DefinitionFile sharedParametersFile = default(Autodesk.Revit.DB.DefinitionFile);

            sharedParametersFile = application.OpenSharedParameterFile();

            return(sharedParametersFile);
        }
Ejemplo n.º 7
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.º 8
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.º 9
0
        public static void RawCreateProjectParameterFromNewSharedParameter(RvtApplication app, string defGroup, string name, ParameterType type, bool visible, CategorySet cats, BuiltInParameterGroup paramGroup, bool inst)
        {
            DefinitionFile defFile = app.OpenSharedParameterFile();

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

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

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

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

            map.Insert(def, binding, paramGroup);
        }
Ejemplo n.º 10
0
        private DefinitionFile OpenSharedParametersFile(Autodesk.Revit.ApplicationServices.Application application)
        {
            StreamWriter stream = default(StreamWriter);

            stream = new StreamWriter(fullFile_Parameters);
            stream.Close();

            application.SharedParametersFilename = fullFile_Parameters;

            Autodesk.Revit.DB.DefinitionFile sharedParametersFile = default(Autodesk.Revit.DB.DefinitionFile);

            sharedParametersFile = application.OpenSharedParameterFile();

            return(sharedParametersFile);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Create project parameter from existing shared parameter
        /// </summary>
        /// <param name="app"></param>
        /// <param name="name"></param>
        /// <param name="cats"></param>
        /// <param name="group"></param>
        /// <param name="inst"></param>
        public static void RawCreateProjectParameterFromExistingSharedParameter(Autodesk.Revit.ApplicationServices.Application app, string name, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            //Location of the shared parameters
            string oriFile = app.SharedParametersFilename;

            //My Documents
            var newpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            //Create txt inside my documents
            Extract("RenumberParts", newpath, "Resources", "SP_RenumberParts.txt");

            //Create variable with the location on SP.txt inside my documents
            string tempFile = newpath + @"\SP_RenumberParts.txt";

            //Change the location of the shared parameters for the SP location
            app.SharedParametersFilename = tempFile;
            DefinitionFile defFile = app.OpenSharedParameterFile();

            var v = (from DefinitionGroup dg in defFile.Groups
                     from ExternalDefinition d in dg.Definitions
                     where d.Name == name
                     select d);


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

            ExternalDefinition def = v.First();

            //Place original SP file
            app.SharedParametersFilename = oriFile;

            //Delete SP temporary file
            System.IO.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.º 12
0
        /// <summary>
        /// Get a definition group if there exists one, otherwise, a new one will be created.
        /// </summary>
        /// <returns>Definition group</returns>
        private DefinitionGroup GetOrCreateDefinitionGroup()
        {
            DefinitionFile file = null;

            int count = 0;

            // A count is to avoid infinite loop
            while (null == file && count < 100)
            {
                file = m_rvtApp.OpenSharedParameterFile();
                if (file == null)
                {
                    // If Shared parameter file does not exist, then create a new one.
                    string shapeFile =
                        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
                        + "\\ParameterFile.txt";

                    // Fill Schema data of Revit shared parameter file.
                    // If no this schema data, OpenSharedParameterFile may alway return null.
                    System.Text.StringBuilder contents = new System.Text.StringBuilder();
                    contents.AppendLine("# This is a Revit shared parameter file.");
                    contents.AppendLine("# Do not edit manually.");
                    contents.AppendLine("*META	VERSION	MINVERSION");
                    contents.AppendLine("META	2	1");
                    contents.AppendLine("*GROUP	ID	NAME");
                    contents.AppendLine("*PARAM	GUID	NAME	DATATYPE	DATACATEGORY	GROUP	VISIBLE");

                    // Write Schema data of Revit shared parameter file.
                    File.WriteAllText(shapeFile, contents.ToString());

                    // Set Revit shared parameter file
                    m_rvtApp.SharedParametersFilename = shapeFile;
                }

                // To avoid infinite loop.
                ++count;
            }

            // Get or create a definition group "Rebar Shape Parameters".
            DefinitionGroup group = file.Groups.get_Item("Rebar Shape Parameters");

            if (group == null)
            {
                group = file.Groups.Create("Rebar Shape Parameters");
            }
            return(group);
        }
Ejemplo n.º 13
0
        public static DefinitionFile CreateSharedParameterFile(this Autodesk.Revit.ApplicationServices.Application app)
        {
            string sharedParametersFilename = app.SharedParametersFilename;

            try
            {
                // Create Temp Shared Parameters File
                app.SharedParametersFilename = Path.GetTempFileName();
                return(app.OpenSharedParameterFile());
            }
            finally
            {
                // Restore User Shared Parameters File
                try { File.Delete(app.SharedParametersFilename); }
                finally { app.SharedParametersFilename = sharedParametersFilename; }
            }
        }
Ejemplo n.º 14
0
        public LoadToFamilyForm(Document document, Autodesk.Revit.ApplicationServices.Application application)
        {
            InitializeComponent();

            app = application;
            doc = document;

            definitionfile = app.OpenSharedParameterFile();

            List <string> groupList = new SharedParametersLibrary(doc, app).GetDefinitionGroupList();
            Dictionary <string, BuiltInParameterGroup> builtInParameterGroupDictionary = new SharedParametersLibrary(doc, app).BuiltInParameterGroupDictionary(doc);

            GroupSelectComboBox.Items.AddRange(groupList.ToArray());
            ParameterList.Items.Add("Please select a group.");
            GroupParameterUnderComboBox.Items.AddRange(builtInParameterGroupDictionary.Keys.ToArray());
            InstanceCheck.Checked = true;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// load family parameters from the text file
        /// </summary>
        /// <param name="exist">
        /// indicate whether the shared parameter file exists
        /// </param>
        /// <returns>
        /// return true if succeeded; otherwise false
        /// </returns>
        private bool LoadSharedParameterFromFile(out bool exist)
        {
            string         usrFilePath     = "";
            string         myDocsFolder    = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = myDocsFolder;
            openFileDialog1.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex      = 1;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Title            = "Please Select the Shared Parameter File";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                usrFilePath = openFileDialog1.FileName;

                exist = true;
                string filePath = usrFilePath;
                if (!File.Exists(filePath))
                {
                    exist = false;
                    return(true);
                }

                m_app.SharedParametersFilename = filePath;
                try
                {
                    m_sharedFile = m_app.OpenSharedParameterFile();
                }
                catch (System.Exception e)
                {
                    MessageManager.MessageBuff.AppendLine(e.Message);
                    return(false);
                }
                return(true);
            }
            else
            {
                exist = false;
                return(false);
            }
        }
        //Gets a SharedParameter
        private ExternalDefinition GetSharedParameter(Autodesk.Revit.ApplicationServices.Application app, string name)
        {
            DefinitionFile defFile = app.OpenSharedParameterFile();

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

            var v = (from DefinitionGroup dg in defFile.Groups
                     from ExternalDefinition d in dg.Definitions
                     where d.Name == name
                     select d);

            if (v == null || v.Count() < 1)
            {
                return(null);                                           //There is no Shared parameter with this name
            }
            ExternalDefinition def = v.First();

            return(def);
        }
Ejemplo n.º 17
0
        public bool LoadSharedParameterFile()
        {
            string         myDocsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            OpenFileDialog ofd          = new OpenFileDialog();

            ofd.InitialDirectory = myDocsFolder;
            ofd.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            ofd.FilterIndex      = 1;
            ofd.RestoreDirectory = true;
            ofd.Title            = "Please Select the Shared Parameter File";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                m_sharedFilePath = ofd.FileName;
                if (!File.Exists(m_sharedFilePath))
                {
                    return(true);
                }

                m_app.SharedParametersFilename = m_sharedFilePath;
                try
                {
                    m_sharedFile = m_app.OpenSharedParameterFile();
                }
                catch (System.Exception e)
                {
                    MessageBox.Show(e.Message);
                    return(false);
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// load family parameters from the text file
        /// </summary>
        /// <param name="exist">
        /// indicate whether the shared parameter file exists
        /// </param>
        /// <returns>
        /// return true if succeeded; otherwise false
        /// </returns>
        private bool LoadSharedParameterFromFile(out bool exist)
        {
            exist = true;
            string filePath = m_assemblyPath + "\\SharedParameter.txt";

            if (!File.Exists(filePath))
            {
                exist = false;
                return(true);
            }

            m_app.SharedParametersFilename = filePath;
            try
            {
                m_sharedFile = m_app.OpenSharedParameterFile();
            }
            catch (System.Exception e)
            {
                MessageManager.MessageBuff.AppendLine(e.Message);
                return(false);
            }

            return(true);
        }
        //Gets a SharedParameter
        private ExternalDefinition GetSharedParameter(Autodesk.Revit.ApplicationServices.Application app, string name)
        {
            DefinitionFile defFile = app.OpenSharedParameterFile();

            if (defFile == null)
            {
                DialogUtils.Failure("Error", $"Shared parameters file does not exist. You are trying to push a Shared Parameter into another Family - make sure you have setup a Shared Parameters file.");
                return(null);
                //throw new Exception("No SharedParameter File!");
            }

            var v = (from DefinitionGroup dg in defFile.Groups
                     from ExternalDefinition d in dg.Definitions
                     where d.Name == name
                     select d);

            if (v == null || v.Count() < 1)
            {
                return(null);                                           //There is no Shared parameter with this name
            }
            ExternalDefinition def = v.First();

            return(def);
        }
Ejemplo n.º 20
0
        public bool BindSharedParameters(string filePath, bool isInstance)
        {
            string         filepath   = filePath;
            bool           isinstance = isInstance;
            DefinitionFile file       = null;

            m_app.SharedParametersFilename = filepath;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        default:
                            bpg = BuiltInParameterGroup.INVALID;
                            break;
                        }

                        m_manager.AddParameter(def, bpg, isinstance);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 将外部共享参数创建为项目参数,并将其绑定到指定的类别
        /// </summary>
        /// <param name="transDoc"> bindingMap.Insert 与 bindingMap.ReInsert 方法必须在事务内才能执行</param>
        /// <param name="doc"></param>
        /// <param name="facenCategoryId"> 面层对象所属的类别 </param>
        public void BindParametersToCategory(Transaction transDoc, Document doc, ElementId facenCategoryId)
        {
            // 打开共享文件
            Autodesk.Revit.ApplicationServices.Application app = doc.Application;
            string OriginalSharedFileName = app.SharedParametersFilename;    // Revit程序中,原来的共享文件路径

            app.SharedParametersFilename = ProjectPath.SharedParameters;     // 设置Revit的共享参数文件

            DefinitionFile myDefinitionFile = app.OpenSharedParameterFile(); // 如果没有找到对应的文件,则打开时不会报错,而是直接返回Nothing
            // app.SharedParametersFilename = OriginalSharedFileName; // 将Revit程序中的共享文件路径还原,以隐藏插件程序中的共享参数文件。

            // create a new group in the shared parameters file
            DefinitionGroup myGroup = myDefinitionFile.Groups.get_Item(FaceWallParameters.sp_Group_Face);

            // 提取此共享参数组中的每一个参数,并赋值给指定的类别
            ExternalDefinition exdef_FaceIdTag = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_FaceIdTag);
            ExternalDefinition exdef_FaceType  = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_FaceType);
            ExternalDefinition exdef_Volumn    = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_Volumn);
            ExternalDefinition exdef_Area      = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_Area);

            //
            BindingMap bindingMap = doc.ParameterBindings;
            Category   myCategory = Category.GetCategory(doc, facenCategoryId);

            // ---------------------------------------------------------------------------------------------------------
            // 判断指定的类别中是否绑定有此 "面层标识 FaceIdTag" 参数
            bool faceParaHasInsertedIntoThatCategory = false;
            bool parameterHasBeenAddedToProject      = false;

            if (bindingMap.Contains(exdef_FaceIdTag))
            {
                Autodesk.Revit.DB.Binding parameterBinding = doc.ParameterBindings.get_Item(exdef_FaceIdTag);
                parameterHasBeenAddedToProject = true;

                if (parameterBinding is InstanceBinding)
                {
                    // 外部共享参数 exdef_FaceIdTag 在此文档中 绑定到了哪些类别
                    CategorySet bindedCategories = ((InstanceBinding)parameterBinding).Categories;
                    if (bindedCategories.Contains(myCategory))
                    {
                        faceParaHasInsertedIntoThatCategory = true;
                    }
                }
            }

            // ---------------------------------------------------------------------------------------------------------
            // 如果此参数"面层标识 FaceIdTag"还没有被添加到项目参数中,则先将用 Insert 其进行添加
            if (!parameterHasBeenAddedToProject)
            {
                //  在“项目参数”中添加此参数,并为其指定一个绑定的类别。
                CategorySet myCategories = app.Create.NewCategorySet();
                myCategories.Insert(myCategory);

                //Create an instance of InstanceBinding
                InstanceBinding instanceBinding = app.Create.NewInstanceBinding(myCategories);
                // Get the BingdingMap of current document.

                // Bind the definitions to the document
                bindingMap.Insert(exdef_FaceIdTag, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);  //  此 Insert 操作必须在事务开启后才能执行
                bindingMap.Insert(exdef_FaceType, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                bindingMap.Insert(exdef_Volumn, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                bindingMap.Insert(exdef_Area, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
            }

            // ---------------------------------------------------------------------------------------------------------
            // 如果"面层标识 FaceIdTag" 参数已经绑定到了指定的类别上,就认为其他三个参数也绑定上来了,此时就不需要再绑定了;
            // 如果没有绑定,则要将这四个参数一次性全部绑定到此指定的类别上
            if (parameterHasBeenAddedToProject && !faceParaHasInsertedIntoThatCategory)
            {
                Autodesk.Revit.DB.Binding parameterBinding = doc.ParameterBindings.get_Item(exdef_FaceIdTag);
                ((InstanceBinding)parameterBinding).Categories.Insert(myCategory);  // 将新的类别添加到 binding 的类别集合中

                // 重新进行绑定
                bindingMap.ReInsert(exdef_FaceIdTag, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                bindingMap.ReInsert(exdef_FaceType, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                bindingMap.ReInsert(exdef_Volumn, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
                bindingMap.ReInsert(exdef_Area, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA);
            }
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
0
        private void StoreSharedParams()
        {
            using (Transaction trans = new Transaction(doc))
            {
                trans.Start("Store Shared Parameters");
                try
                {
                    string currentAssembly = System.Reflection.Assembly.GetAssembly(this.GetType()).Location;
                    string definitionPath  = Path.GetDirectoryName(currentAssembly) + "/Resources/Mass Shared Parameters.txt";
                    m_app.SharedParametersFilename = definitionPath;
                    definitionFile = m_app.OpenSharedParameterFile();

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

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

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

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

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

                        foreach (string paramName in activeSharedParams)
                        {
                            definition = definitions.get_Item("Mass_" + paramName);
                            if (null == definition)
                            {
#if RELEASE2013 || RELEASE2014
                                Parameter param = element.get_Parameter(paramName);
                                definition = definitions.Create("Mass_" + param.Definition.Name, param.Definition.ParameterType);
#elif RELEASE2015
                                Parameter param = element.LookupParameter(paramName);
                                ExternalDefinitonCreationOptions options = new ExternalDefinitonCreationOptions("Mass_" + param.Definition.Name, param.Definition.ParameterType);
                                definition = definitions.Create(options);
#elif RELEASE2016
                                Parameter param = element.LookupParameter(paramName);
                                ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions("Mass_" + param.Definition.Name, param.Definition.ParameterType);
                                definition = definitions.Create(options);
#endif
                            }
                            if (null != definition && !defDictionary.ContainsKey(paramName))
                            {
                                defDictionary.Add(paramName, definition);
                            }
                        }
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to store shared parameters.\n" + ex.Message, "Form_RoomMass:StoreSharedParams", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    trans.RollBack();
                }
            }
        }
 public SharedParametersLibrary(Document document, Autodesk.Revit.ApplicationServices.Application application)
 {
     app            = application;
     doc            = document;
     definitionfile = app.OpenSharedParameterFile();
 }
Ejemplo n.º 25
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document famdoc = commandData.Application.ActiveUIDocument.Document;

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

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

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

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

            string familyPath = openDialog.FileName;

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


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

            fs.Close();

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

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

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

            FamilyManager fMan = famdoc.FamilyManager;

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

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



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

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

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

            return(Result.Succeeded);
        }