/// <summary>
        /// Returns shared or built-in parameter of the specified name. parameter.IsShared property identifies the type.
        /// If it does not exist it is created in the shared parameters file with specified name in the specified group. That must be defined in advance
        /// using SetDefinitionFile() function.
        /// </summary>
        /// <param name="paramType">Type of the parameter (simplified to base data types)</param>
        /// <param name="groupName">Name of the group of the shared parameters</param>
        /// <param name="parameterName">Name of the parameter</param>
        /// <param name="group">Revit built in parameter group where the parameter is to be created if it doesn't exist</param>
        /// <returns>Existing or new parameter</returns>
        public static Parameter GetParameter(this Element element, ParameterType paramType, string parameterName, BuiltInParameterGroup group)
        {
            Parameter parameter = element.get_Parameter(parameterName);
            if (parameter != null)
            {
                //check type and throw error if the type is different
                if (parameter.Definition.ParameterType == paramType)
                    return parameter; //returns existing parameter (it could be any type of parameter not only shared parameter)
                else
                    throw new Exception(String.Format("Parameter type mismatch for pID '{0}': existing type: {1}, desired type {2}.", parameterName, parameter.Definition.ParameterType, paramType));
            }

            // Create a category set and insert category of wall to it
            CategorySet myCategories = element.Document.Application.Create.NewCategorySet();
            // Use BuiltInCategory to get category of wall
            Category myCategory = element.Category;

            myCategories.Insert(myCategory);

            bool success = SetNewSharedParameter(element, paramType, myCategories, parameterName, group);

            if (!success)
            {
                Debug.WriteLine("Parameter creation not successfull.\nParameter name: " + parameterName + "\n Existing parameters:");
                foreach (Parameter par in element.Parameters)
                {
                    Debug.WriteLine("Parameter name: " + par.Definition.Name + ", group: " + Enum.GetName(typeof(BuiltInParameterGroup), par.Definition.ParameterGroup));
                }
                throw new Exception("Parameter creation failed.");
            }

            parameter = element.get_Parameter(parameterName);
            return parameter;
        }
 /// <summary>
 /// Find, or create, the map of parameter name to parameter for a parameter group.
 /// </summary>
 /// <param name="key">The parameter group.</param>
 /// <returns>The map of parameter name to parameter for the parameter group.</returns>
 private IDictionary<string, Parameter> Find(BuiltInParameterGroup key)
 {
     IDictionary<string, Parameter> value = null;
     if (!m_ParameterByGroup.TryGetValue(key, out value))
     {
         value = new SortedDictionary<string, Parameter>();
         m_ParameterByGroup[key] = value;
     }
     return value;
 }
Пример #3
0
        /// <summary>
        /// Cache the parameters for an element, allowing quick access later.
        /// </summary>
        /// <param name="id">The element id.</param>
        static private void CacheParametersForElement(ElementId id)
        {
            if (id == ElementId.InvalidElementId)
            {
                return;
            }

            if (m_NonIFCParameters.ContainsKey(id))
            {
                return;
            }

            IDictionary <BuiltInParameterGroup, ParameterElementCache> nonIFCParameters = new SortedDictionary <BuiltInParameterGroup, ParameterElementCache>();
            ParameterElementCache ifcParameters = new ParameterElementCache();

            m_NonIFCParameters[id] = nonIFCParameters;
            m_IFCParameters[id]    = ifcParameters;

            Element element = ExporterCacheManager.Document.GetElement(id);

            if (element == null)
            {
                return;
            }

            ParameterSet parameterIds = element.Parameters;

            if (parameterIds.Size == 0)
            {
                return;
            }

            // We will do two passes.  In the first pass, we will look at parameters in the IFC group.
            // In the second pass, we will look at all other groups.
            ParameterSetIterator parameterIt = parameterIds.ForwardIterator();

            while (parameterIt.MoveNext())
            {
                Parameter parameter = parameterIt.Current as Parameter;
                if (parameter == null)
                {
                    continue;
                }

                if (IsDuplicateParameter(parameter))
                {
                    continue;
                }

                Definition paramDefinition = parameter.Definition;
                if (paramDefinition == null)
                {
                    continue;
                }

                // Don't cache parameters that aren't visible to the user.
                InternalDefinition internalDefinition = paramDefinition as InternalDefinition;
                if (internalDefinition != null && internalDefinition.Visible == false)
                {
                    continue;
                }

                if (string.IsNullOrWhiteSpace(paramDefinition.Name))
                {
                    continue;
                }

                string cleanPropertyName = NamingUtil.RemoveSpaces(paramDefinition.Name);

                BuiltInParameterGroup groupId       = paramDefinition.ParameterGroup;
                ParameterElementCache cacheForGroup = null;

                if (groupId != BuiltInParameterGroup.PG_IFC)
                {
                    if (!nonIFCParameters.TryGetValue(groupId, out cacheForGroup))
                    {
                        cacheForGroup             = new ParameterElementCache();
                        nonIFCParameters[groupId] = cacheForGroup;
                    }
                }
                else
                {
                    cacheForGroup = ifcParameters;
                }

                if (cacheForGroup != null)
                {
                    // We may have situations (due to bugs) where a parameter with the same name appears multiple times.
                    // In this case, we will preserve the first parameter with a value.
                    // Note that this can still cause inconsistent behavior in the case where multiple parameters with the same
                    // name have values, and we should warn about that when we start logging.
                    if (!cacheForGroup.ParameterCache.ContainsKey(cleanPropertyName) ||
                        !cacheForGroup.ParameterCache[cleanPropertyName].HasValue)
                    {
                        cacheForGroup.ParameterCache[cleanPropertyName] = parameter;
                    }
                }
            }
        }
        /// <summary>
        /// Cache the parameters for an element, allowing quick access later.
        /// </summary>
        /// <param name="id">The element id.</param>
        static private void CacheParametersForElement(ElementId id)
        {
            if (id == ElementId.InvalidElementId)
            {
                return;
            }

            if (m_NonIFCParameters.ContainsKey(id))
            {
                return;
            }

            IDictionary <BuiltInParameterGroup, ParameterElementCache> nonIFCParameters = new SortedDictionary <BuiltInParameterGroup, ParameterElementCache>();
            ParameterElementCache ifcParameters = new ParameterElementCache();

            m_NonIFCParameters[id] = nonIFCParameters;
            m_IFCParameters[id]    = ifcParameters;

            Element element = ExporterCacheManager.Document.GetElement(id);

            if (element == null)
            {
                return;
            }

            ParameterSet parameterIds = element.Parameters;

            if (parameterIds.Size == 0)
            {
                return;
            }

            // We will do two passes.  In the first pass, we will look at parameters in the IFC group.
            // In the second pass, we will look at all other groups.
            ParameterSetIterator parameterIt = parameterIds.ForwardIterator();

            while (parameterIt.MoveNext())
            {
                Parameter parameter = parameterIt.Current as Parameter;
                if (parameter == null)
                {
                    continue;
                }

                if (IsDuplicateParameter(parameter))
                {
                    continue;
                }

                Definition paramDefinition = parameter.Definition;
                if (paramDefinition == null)
                {
                    continue;
                }

                // Don't cache parameters that aren't visible to the user.
                InternalDefinition internalDefinition = paramDefinition as InternalDefinition;
                if (internalDefinition != null && internalDefinition.Visible == false)
                {
                    continue;
                }

                if (string.IsNullOrWhiteSpace(paramDefinition.Name))
                {
                    continue;
                }

                string cleanPropertyName = NamingUtil.RemoveSpaces(paramDefinition.Name);

                BuiltInParameterGroup groupId = paramDefinition.ParameterGroup;
                if (groupId != BuiltInParameterGroup.PG_IFC)
                {
                    ParameterElementCache cacheForGroup = null;
                    if (!nonIFCParameters.TryGetValue(groupId, out cacheForGroup))
                    {
                        cacheForGroup             = new ParameterElementCache();
                        nonIFCParameters[groupId] = cacheForGroup;
                    }
                    cacheForGroup.ParameterCache[cleanPropertyName] = parameter;
                }
                else
                {
                    ifcParameters.ParameterCache[cleanPropertyName] = parameter;
                }
            }
        }
        public void settingFamilyParamentersValue(Document doc, string familyFilePath, string parameterFilePath)
        {
            //读取xls文件
            ExcelHelper ExcelHelper = new ExcelHelper();
            DataTable   dt          = ExcelHelper.Reading_Excel_Information(parameterFilePath);

            //获取参数集
            FamilyParameterSet rfadocParas         = doc.FamilyManager.Parameters;
            List <string>      rfadocParasListName = new List <string>();

            foreach (FamilyParameter rfadocPara in rfadocParas)
            {
                rfadocParasListName.Add(rfadocPara.Definition.Name);
            }

            #region
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                List <string> ls_ParameterNames = new List <string>();
                //ls_ParameterNames.Add(dt.Rows[i][0].ToString);
            }
            #endregion

            #region 族参数操作1
            FamilyManager familyMgr = doc.FamilyManager;

            //清空族内所有类型 仅保留默认族类型
            int typesizes = familyMgr.Types.Size;
            if (familyMgr.Types.Size > 1 && familyMgr.Types.Size != 0)
            {
                for (int typenumber = 0; typenumber < typesizes - 1; typenumber++)
                {
                    if (familyMgr.CurrentType != null)
                    {
                        Transaction DeleteType = new Transaction(doc, "DeleteType");
                        DeleteType.Start();
                        familyMgr.DeleteCurrentType();
                        DeleteType.Commit();
                    }
                }
            }

            //清空族内所有参数条目
            foreach (FamilyParameter fp in familyMgr.Parameters)
            {
                if (fp.Definition.ParameterGroup == BuiltInParameterGroup.PG_ELECTRICAL)
                {
                    Transaction RemoveParameter = new Transaction(doc, "RemoveParameter");
                    RemoveParameter.Start();
                    familyMgr.RemoveParameter(fp);
                    RemoveParameter.Commit();
                }
            }

            //开始添加

            Transaction addParameter = new Transaction(doc, "AddParameters");
            addParameter.Start();

            List <string> paraNames   = new List <string>();
            List <bool>   isInstances = new List <bool>();
            List <string> paravalues  = new List <string>();
            //设置族参数的类别和类型
            BuiltInParameterGroup paraGroup   = BuiltInParameterGroup.PG_ELECTRICAL;
            BuiltInParameterGroup paraGroupEx = BuiltInParameterGroup.PG_GENERAL;
            ParameterType         paraType    = ParameterType.Text;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string paraName = dt.Rows[i]["paraname"].ToString();
                paraNames.Add(paraName);

                //设置族参数为实例参数
                bool isInstance = true;
                if (dt.Rows[i]["paratag"].ToString() == "是")
                {
                    isInstance = true;
                }
                else
                {
                    isInstance = false;
                }
                isInstances.Add(isInstance);

                paravalues.Add(dt.Rows[i]["paravalue"].ToString());
            }

            for (int k = 0; k < paraNames.Count(); k++)
            {
                int tag = 0;
                if (paraNames[k].Contains("M_") || paraNames[k].Contains("D_") || paraNames[k].Contains("设计-") || paraNames[k].Contains("管理-"))
                {
                    FamilyParameter newParameter = familyMgr.AddParameter(paraNames[k], paraGroup, paraType, isInstances[k]);
                    //创建族参数(每个参数两秒)
                    familyMgr.Set(newParameter, paravalues[k]);
                }
                else
                {
                    foreach (var fpln in rfadocParasListName)
                    {
                        if (paraNames[k] == fpln)
                        {
                            tag = 1;
                        }
                    }
                    if (tag == 1)
                    {
                        continue;
                    }
                    else
                    {
                        FamilyParameter newParameter = familyMgr.AddParameter(paraNames[k], paraGroupEx, paraType, isInstances[k]);
                    }
                }
            }
            SaveOptions opt = new SaveOptions();
            //doc.Save(opt);
            //doc.SaveAs(@"D:\"+);
            //doc.Close();
            addParameter.Commit();
            #endregion
        }
Пример #6
0
        private void BtnAddParameters_Click(object sender, EventArgs e)
        {
            #region get all checked parameters
            List <Definition> defList = new List <Definition>();
            foreach (TreeNode n1 in TreeViewParameters.Nodes)
            {
                foreach (TreeNode n2 in n1.Nodes)
                {
                    if (n2.Checked == true)
                    {
                        defList.Add(n2.Tag as Definition);
                    }
                }
            }
            #endregion

            #region get all checked categories
            List <Category> catList = new List <Category>();
            if (m_doc.IsFamilyDocument == true)
            {
                catList.Add(m_doc.OwnerFamily.FamilyCategory);
            }
            else
            {
                foreach (TreeNode c in TreeViewCategories.Nodes)
                {
                    if (c.Checked == true)
                    {
                        catList.Add(c.Tag as Category);
                    }
                }
            }
            #endregion

            // Check if selected: Shared Parameter FILE, Parameters and Categories
            if (m_app.OpenSharedParameterFile() == null
                | defList.Count == 0
                | catList.Count == 0)
            {
                using (UI.Info.Form_Info1 thisForm = new UI.Info.Form_Info1())
                {
                    thisForm.ShowDialog();
                }
            }

            // Load parameters
            else
            {
                // get parameter group
                KeyValuePair <BuiltInParameterGroup, string> groupKeyValuePair = (KeyValuePair <BuiltInParameterGroup, string>)CbxGroup.SelectedItem;
                BuiltInParameterGroup group = groupKeyValuePair.Key;

                // Bind the Definitions
                Data.Helpers.BindDefinitionsToCategories(m_doc,
                                                         m_app,
                                                         defList,
                                                         catList,
                                                         group,
                                                         RbtInstance.Checked);
                // show Results Form
                using (UI.Info.Form_Results thisForm = new Info.Form_Results())
                {
                    thisForm.ShowDialog();
                }

                // show form Do you want to load more parameters?
                using (UI.Info.Form_Info2 thisForm = new UI.Info.Form_Info2())
                {
                    thisForm.ShowDialog();
                    if (thisForm.DialogResult == DialogResult.No)
                    {
                        this.DialogResult = DialogResult.OK;
                    }
                }

                // uncheck parameters
                foreach (TreeNode n in TreeViewParameters.Nodes) // parents
                {
                    n.Checked = false;

                    foreach (TreeNode c in n.Nodes) // children
                    {
                        c.Checked = false;
                    }
                }
                // uncheck categories
                foreach (TreeNode n in TreeViewCategories.Nodes)
                {
                    n.Checked = false;
                }
            }
        }
        public ElementBinding Add(Document document, string name, IEnumerable <BuiltInCategory> builtInCategories, BuiltInParameterGroup builtInParameterGroup, bool instance)
        {
            if (document == null || document.ParameterBindings == null || string.IsNullOrWhiteSpace(name) || builtInCategories == null || builtInCategories.Count() == 0)
            {
                return(null);
            }

            ElementBinding result = null;

            DefinitionBindingMapIterator definitionBindingMapIterator = document?.ParameterBindings?.ForwardIterator();

            if (definitionBindingMapIterator != null)
            {
                definitionBindingMapIterator.Reset();

                while (definitionBindingMapIterator.MoveNext())
                {
                    Definition definition_Temp = definitionBindingMapIterator.Key as Definition;
                    if (definition_Temp == null)
                    {
                        continue;
                    }

                    //if (aExternalDefinition.GUID.Equals(pExternalDefinition.GUID))
                    if (definition_Temp.Name.Equals(name))
                    {
                        result = (ElementBinding)definitionBindingMapIterator.Current;
                        break;
                    }
                }
            }

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

            Definition definition = Find(name);

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

            CategorySet categorySet = Revit.Create.CategorySet(document, builtInCategories);

            if (categorySet == null || categorySet.Size == 0)
            {
                return(null);
            }

            if (result != null)
            {
            }
            else
            {
                if (instance)
                {
                    result = document.Application.Create.NewInstanceBinding(categorySet);
                }
                else
                {
                    result = document.Application.Create.NewTypeBinding(categorySet);
                }

                document.ParameterBindings.Insert(definition, result, builtInParameterGroup);
            }

            return(result);
        }
Пример #8
0
        public ElementBindingData(string name, IEnumerable <BuiltInCategory> builtInCategories, BuiltInParameterGroup builtInParameterGroup, bool instance)
        {
            this.name = name;
            if (builtInCategories != null)
            {
                this.builtInCategories = new HashSet <BuiltInCategory>();
                foreach (BuiltInCategory builtInCategory in builtInCategories)
                {
                    this.builtInCategories.Add(builtInCategory);
                }
            }

            this.builtInParameterGroup = builtInParameterGroup;
            this.instance = instance;
        }
Пример #9
0
        public static void sharedParameterEkle(RevitApplication app, string name, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            DefinitionFile defFile = app.OpenSharedParameterFile();

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

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

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

            map.Insert(def, binding, group);
        }
Пример #10
0
 public ParameterInfo()
 {
     this.m_parameterGroup = (BuiltInParameterGroup)(-1);
     this.m_parameterType  = (ParameterType)1;
 }
Пример #11
0
        public QaqcRFSPRequest(UIApplication uiApp, String text)
        {
            MainUI        uiForm      = BARevitTools.Application.thisApp.newMainUi;
            List <string> familyFiles = uiForm.qaqcRFSPFamilyFiles;

            foreach (string familyFile in familyFiles)
            {
                //Open the family file and get its Family Manager. Then, get the list of family parameters
                RVTDocument             familyDoc = uiApp.Application.OpenDocumentFile(familyFile);
                FamilyManager           famMan    = familyDoc.FamilyManager;
                IList <FamilyParameter> famParams = famMan.GetParameters();
                string famName = familyDoc.Title.Replace(".rfa", "");
                //Start a transaction
                using (Transaction t1 = new Transaction(familyDoc, "ChangeSharedParameters"))
                {
                    t1.Start();
                    try
                    {
                        //Cycle through the family parameters
                        foreach (FamilyParameter param in famParams)
                        {
                            string paramName = param.Definition.Name;
                            try
                            {
                                //If the parameter is shared, and the name does not contain BA or BAS, continue
                                if (param.IsShared && !paramName.ToUpper().Contains("BA ") && !paramName.ToUpper().Contains("BAS "))
                                {
                                    //A temporary parameter needs to be made in the place of the one to be removed, so get the group of the parameter to be replaced
                                    BuiltInParameterGroup paramGroup = param.Definition.ParameterGroup;
                                    string paramTempName             = "tempName";
                                    //Determine if the parameter to replaced is an instance parameter
                                    bool paramInstance = param.IsInstance;
                                    //Make replace the parameter with the temporary one, giving it the same group and instance settings
                                    FamilyParameter newParam = famMan.ReplaceParameter(param, paramTempName, paramGroup, paramInstance);
                                    //Then, rename the new parameter
                                    famMan.RenameParameter(newParam, paramName);
                                    //Add to the ListBox the outcome of the shared parameter replacement
                                    uiForm.qaqcRFSPParametersListBox.Items.Add(famName + " : " + paramName + ": SUCCESS");
                                }
                            }
                            catch
                            {
                                //If the replacement fails, report that too
                                uiForm.qaqcRFSPParametersListBox.Items.Add(famName + " : " + paramName + ": FAILED");
                            }
                        }
                        t1.Commit();
                        //Update the MainUI
                        uiForm.qaqcRFSPParametersListBox.Update();
                        uiForm.qaqcRFSPParametersListBox.Refresh();
                    }
                    catch
                    {
                        t1.RollBack();
                    }
                }
                //Save the family and remove the backups
                RVTOperations.SaveRevitFile(uiApp, familyDoc, true);
                GeneralOperations.CleanRfaBackups(Path.GetDirectoryName(familyFile));
            }
        }
Пример #12
0
        /// <summary>
        /// The method generates a new shared parameter,
        /// then binding it to a particular category in a document
        /// </summary>
        /// <param name="parameterName">Shared Parameter Name</param>
        /// <param name="parameterType">Shared Parameter Type</param>
        /// <param name="categories">Categories to bind the parameter to</param>
        /// <param name="parameterGroup"></param>
        /// <param name="isInstance">Whether the parameter is an instance or type one</param>
        /// <param name="isModifiable">Whether the user is allowed to modify the parameter</param>
        /// <param name="isVisible">Is it visible to the user</param>
        /// <param name="defGroupName">The name of a group in a shared parameter file</param>
        /// <param name="createTmpFile">Is a temp shared parameter file to be generated</param>
        /// <param name="guid">The guid of the shared parameter</param>
        internal void CreateSharedParameter(
            string parameterName,
            ParameterType parameterType,
            IList <BuiltInCategory> categories,
            BuiltInParameterGroup parameterGroup,
            bool isInstance, bool isModifiable, bool isVisible,
            string defGroupName = "Custom", bool createTmpFile = false,
            Guid guid           = default(Guid))
        {
            string tempFilePath = null;

            try {
                // Get access to the file
                DefinitionFile defFile =
                    m_doc.Application.OpenSharedParameterFile();

                if (defFile == null || createTmpFile)
                {
                    // set the location of a new .txt file
                    tempFilePath =
                        System.IO.Path.GetTempFileName() + ".txt";

                    // Create the .txt file containing shared parameter definitions
                    using (System.IO.Stream s = System.IO.File.Create(tempFilePath)) {
                        s.Close();
                    }

                    // set the file as a shared parameter source file to the application
                    m_doc.Application.SharedParametersFilename = tempFilePath;
                    defFile =
                        m_doc.Application.OpenSharedParameterFile();
                }

                // Create a new group called
                DefinitionGroup defGroup =
                    defFile.Groups.FindDefinitionGroup(defGroupName);
                if (defGroup == null)
                {
                    defGroup = defFile.Groups.Create(defGroupName);
                }

                // Create a new defintion
                ExternalDefinitionCreationOptions defCrtOptns =
                    new ExternalDefinitionCreationOptions
                        (parameterName, parameterType);
                defCrtOptns.UserModifiable = isModifiable;
                defCrtOptns.Visible        = isVisible;
                if (guid != default(Guid))
                {
                    defCrtOptns.GUID = guid;
                }

                // Insert the definition into the group
                Definition def =
                    defGroup.Definitions.Create(defCrtOptns);

                // Lay out the categories to which the params
                // will be bound
                CategorySet categorySet = new CategorySet();

                foreach (BuiltInCategory category in categories)
                {
                    categorySet.Insert(m_doc.Settings.Categories.get_Item(category));
                }

                // Define a binding type
                Binding binding = null;
                if (isInstance)
                {
                    binding = new InstanceBinding(categorySet);
                }
                else
                {
                    binding = new TypeBinding(categorySet);
                }

                // Bind the parameter to the active document
                using (Transaction t = new Transaction(m_doc)) {
                    t.Start("Add Read Only Parameter");
                    m_doc.ParameterBindings.Insert
                        (def, binding, parameterGroup);
                    t.Commit();
                }

                Autodesk.Revit.UI.TaskDialog.Show("Success",
                                                  string.Format("The paramter {0} has been successfully added to the document",
                                                                def.Name));
            }
            finally {
                if (tempFilePath != null)
                {
                    System.IO.File.Delete(tempFilePath);
                    m_doc.Application.SharedParametersFilename = null;
                }
            }
        }
Пример #13
0
        public void  CreateProjectParameter(string name, Category cat, ParameterType type, BuiltInParameterGroup group, bool inst)
        {
            var def = CreateProjectParameterDefinition(name, type);

            BindParameterDefinition(def, cat, group, inst);
        }
Пример #14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)

        {
            //Get application and documnet objects

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                trans.Start();

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

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

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


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

                trans.Commit();

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

            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                // If user decided to cancel the operation return Result.Canceled
                return(Result.Cancelled);
            }
            catch (Exception ex)
            {
                // If something went wrong return Result.Failed
                message = ex.Message;
                return(Result.Failed);
            }
        }
        private static List <Parameter> ParametersInGroup(Element e, BuiltInParameterGroup g)
        {
            Dictionary <BuiltInParameterGroup, List <Parameter> > groupDict = GroupParameters(e);

            return(groupDict.Keys.Contains(g) ? groupDict[g] : null);
        }
Пример #16
0
        /// <summary>
        /// Проверяет налиxие общего параметра у элемента. Если параметр есть - возвращает его. Иначе добавляет параметр из файла общих параметров.
        /// </summary>
        /// <param name="elem"></param>
        /// <param name="app"></param>
        /// <param name="catset"></param>
        /// <param name="ParameterName"></param>
        /// <param name="paramGroup"></param>
        /// <param name="SetVaryByGroups"></param>
        /// <returns></returns>
        public static Parameter CheckAndAddSharedParameter(Element elem, Application app, CategorySet catset, string ParameterName, BuiltInParameterGroup paramGroup, bool SetVaryByGroups)
        {
            Document  doc   = elem.Document;
            Parameter param = elem.LookupParameter(ParameterName);

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

            string oldSharedParamsFile = app.SharedParametersFilename;

            app.SharedParametersFilename = @"\\picompany.ru\pikp\lib\_CadSettings\02_Revit\04. Shared Parameters\SP-ALL-PIC.txt";

            ExternalDefinition exDef           = null;
            string             sharedFile      = app.SharedParametersFilename;
            DefinitionFile     sharedParamFile = app.OpenSharedParameterFile();

            foreach (DefinitionGroup defgroup in sharedParamFile.Groups)
            {
                foreach (Definition def in defgroup.Definitions)
                {
                    if (def.Name == ParameterName)
                    {
                        exDef = def as ExternalDefinition;
                    }
                }
            }
            if (exDef == null)
            {
                throw new Exception("В файл общих параметров не найден общий параметр " + ParameterName);
            }

            bool checkContains = doc.ParameterBindings.Contains(exDef);

            if (checkContains)
            {
                var res = BindSharedParam(doc, elem, ParameterName, exDef);
            }

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

            doc.ParameterBindings.Insert(exDef, newIB, paramGroup);

            if (SetVaryByGroups)
            {
                doc.Regenerate();

                SharedParameterElement spe    = SharedParameterElement.Lookup(doc, exDef.GUID);
                InternalDefinition     intDef = spe.GetDefinition();
                intDef.SetAllowVaryBetweenGroups(doc, true);
            }
            doc.Regenerate();


            app.SharedParametersFilename = oldSharedParamsFile;
            param = elem.LookupParameter(ParameterName);
            if (param == null)
            {
                throw new Exception("Не удалось добавить обший параметр " + ParameterName);
            }

            return(param);
        }
        /// <summary>
        /// Gets the parameter by name from an element from the parameter cache.
        /// </summary>
        /// <param name="elementId">The element id.</param>
        /// <param name="group">The parameter group.</param>
        /// <param name="propertyName">The property name.</param>
        /// <returns>The Parameter.</returns>
        static private Parameter getParameterByNameFromCache(ElementId elementId, BuiltInParameterGroup group,
            string propertyName)
        {
            Parameter parameter = null;
            string cleanPropertyName = NamingUtil.RemoveSpaces(propertyName);

            if (group == BuiltInParameterGroup.PG_IFC)
            {
                m_IFCParameters[elementId].ParameterCache.TryGetValue(cleanPropertyName, out parameter);
                return null;
            }

            ParameterElementCache otherCache = null;
            m_NonIFCParameters[elementId].TryGetValue(group, out otherCache);
            if (otherCache != null)
                otherCache.ParameterCache.TryGetValue(cleanPropertyName, out parameter);

            return parameter;
        }
Пример #18
0
        public bool AddOrCreateShadeParameter(Document doc, string groupName, string parameterName, Category category, bool isInstance, BuiltInParameterGroup parameterGroup)
        {
            if (this.path == "")
            {
                throw new Exception("路径无效");
            }
            doc.Application.SharedParametersFilename = this.path;
            DefinitionFile   definitionFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroups groups         = definitionFile.Groups;
            DefinitionGroup  group          = groups.get_Item(groupName);

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

            if (definition == null)
            {
                definition = group.Definitions.Create(new ExternalDefinitionCreationOptions(parameterName, ParameterType.Text));
            }

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

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

            if (isInstance)
            {
                binding = doc.Application.Create.NewInstanceBinding(set);
            }
            else
            {
                binding = doc.Application.Create.NewTypeBinding(set);
            }
            doc.ParameterBindings.Remove(definition);
            return(doc.ParameterBindings.Insert(definition, binding, parameterGroup));
        }
Пример #19
0
        /// <summary>
        /// get parameter via matching the appointed name and group.
        /// and deal with it according to the type of Parameter's StorageType
        /// </summary>
        protected Object GetParameterValue(string parameterName, BuiltInParameterGroup parameterGroup)
        {
            ParameterSet parameters = m_bC.Parameters;
            foreach (Parameter parameter in parameters)
            {
                // find the parameter of which the name is the same as the param name
                if ((parameterName != parameter.Definition.Name) ||
                    (parameterGroup != parameter.Definition.ParameterGroup))
                {
                    continue;
                }

                // get the parameter value
                switch (parameter.StorageType)
                {
                    case StorageType.Double:
                        return parameter.AsDouble();
                    case StorageType.Integer:
                        return parameter.AsInteger();
                    case StorageType.ElementId:
                        return parameter.AsElementId();
                    case StorageType.String:
                        return parameter.AsString();
                    case StorageType.None:
                        return parameter.AsValueString();
                    default:
                        return null;
                }
            }

            return null;
        }
Пример #20
0
        /// <summary>
        /// when user changed the parameter value via the UI set this changed parameter value
        /// </summary>
        /// <param name="parameterName">the name of the changed parameter</param>
        /// <param name="parameterGroup">
        /// because some parameters of boundary conditions have the same name
        /// </param>
        /// <param name="value">the new parameter value</param>
        protected void SetParameterValue(string parameterName,
                                         BuiltInParameterGroup parameterGroup, 
                                         Object value)
        {
            ParameterSet parameters = m_bC.Parameters;
            foreach (Parameter parameter in parameters)
            {
                // find the parameter of which the name is the same as the param name
                if ((parameterName != parameter.Definition.Name) ||
                    (parameterGroup != parameter.Definition.ParameterGroup))
                {
                    continue;
                }

                // get the parameter value
                switch (parameter.StorageType)
                {
                    case StorageType.Double:
                        parameter.Set((double)value);
                        break;
                    case StorageType.Integer:
                        parameter.Set((int)value);
                        break;
                    case StorageType.ElementId:
                        Autodesk.Revit.DB.ElementId Id = (Autodesk.Revit.DB.ElementId)value;
                        parameter.Set(Id);
                        break;
                    case StorageType.String:
                        parameter.Set(value as string);
                        break;
                    case StorageType.None:
                        parameter.SetValueString(value as string);
                        break;
                    default:
                        break;
                }
            }
        }
        /// <summary>
        ///  Creates new shared parameter if it does not exist and bind it to the type or instance of the objects 
        /// </summary>
        /// <param name="paramType">Type of the parameter</param>
        /// <param name="categoriesForParam">Category of elements to bind the parameter to</param>
        /// <param name="defaultGroupName">Group name of the parameters</param>
        /// <param name="parameterName">Name of the parameter</param>
        /// <returns>TRUE if shared parameter is created, FALSE otherwise</returns>
        public static bool SetNewSharedParameter(this Element element, ParameterType paramType, CategorySet categoriesForParam, string parameterName, BuiltInParameterGroup group)
        {
            string defaultGroupName = "4P_imported_parameters"; //this is a hack to avoid multiple parameters with the same name.

            if (categoriesForParam == null) return false;
            if (categoriesForParam.Size == 0) return false;
            foreach (Category cat in categoriesForParam)
            {
                if (cat == null) return false;
                if (!cat.AllowsBoundParameters) return false;
            }

            Application application = element.Document.Application;
            Document document = element.Document;
            if (_definitionFile == null)
            {
                //ask for the location of the shared parameters file
                var dialog = new Microsoft.Win32.OpenFileDialog();
                dialog.CheckFileExists = false;
                dialog.Title = "Set shared pID file...";
                dialog.ShowDialog();
                string shrFilePath = dialog.FileName;
                if (shrFilePath == null)
                {
                    _definitionFile = application.OpenSharedParameterFile();
                    if (_definitionFile == null) SetSharedParamFileInUserProgramFolder(document);
                }
                else
                {
                    SetDefinitionFile(element, shrFilePath);
                }
            }
            if (_definitionFile == null) throw new Exception("Definition file must be set before creation of the new parameters.");

            DefinitionFile myDefinitionFile = _definitionFile;

            // Get parameter or create new one
            DefinitionGroups myGroups = myDefinitionFile.Groups;
            Definition myDefinition = null;
            bool found = false;

            foreach (DefinitionGroup gr in myGroups)
            {
                foreach (Definition def in gr.Definitions)
                {
                    if (def.Name == parameterName)
                    {
                        myDefinition = def;
                        found = true;
                        break;
                    }
                }
                if (found) break;
            }

            //if there is not such a parameter new one is created in default group
            if (myDefinition == null)
            {
                DefinitionGroup myGroup = myGroups.get_Item(defaultGroupName);
                if (myGroup == null)
                {
                    myGroup = myGroups.Create(defaultGroupName);
                }

                // Create a type definition
                myDefinition = myGroup.Definitions.get_Item(parameterName);
                if (myDefinition == null)
                {
                    myDefinition = myGroup.Definitions.Create(parameterName, paramType);

                }
            }

            //Create an object of TypeBinding or InstanceBinding according to the Categories and "typeBinding" variable
            Binding binding = null;
            // Get the BingdingMap of current document.
            BindingMap bindingMap = document.ParameterBindings;
            binding = bindingMap.get_Item(myDefinition);

            bool bindOK = false;
            if (!element.CanHaveTypeAssigned() && !(element is Material) && !(element is ProjectInfo))
            {
                if (binding != null)
                {
                    TypeBinding typeBinding = binding as TypeBinding;
                    if (typeBinding == null)
                        throw new Exception("Parameter with this definition already exists and is bound to instances. It cannot be bound to the type at the same time");
                    foreach (Category cat in categoriesForParam) typeBinding.Categories.Insert(cat);
                    bindOK = bindingMap.ReInsert(myDefinition, binding, group);
                    return bindOK;
                }
                else
                {
                    binding = application.Create.NewTypeBinding(categoriesForParam);
                }
            }
            else
            {
                if (binding != null)
                {
                    InstanceBinding instBinding = binding as InstanceBinding;
                    if (instBinding == null)
                        throw new Exception("Parameter with this definition already exists and is bound to types. It cannot be bound to the instance at the same time");
                    foreach (Category cat in categoriesForParam) instBinding.Categories.Insert(cat);
                    bindOK = bindingMap.ReInsert(myDefinition, binding, group);
                    return bindOK;
                }
                else
                {
                    binding = application.Create.NewInstanceBinding(categoriesForParam);
                }
            }

            // Bind the definitions to the document
            bindOK = bindingMap.Insert(myDefinition, binding, group);
            return bindOK;
        }
Пример #22
0
 /// <summary>
 /// constructor which exposes for invoking
 /// </summary>
 /// <param name="name">
 /// parameter name
 /// </param>
 /// <param name="group">
 /// indicate which group the parameter belongs to
 /// </param>
 /// <param name="type">
 /// the type of the parameter
 /// </param>
 /// <param name="isInstance">
 /// indicate whethe the parameter is an instance parameter
 /// </param>
 /// <param name="line">
 /// record the location of this parameter in the family parameter file
 /// </param>
 public FamilyParam(string name, BuiltInParameterGroup group, ParameterType type, bool isInstance, int line)
 {
    m_name = name;
    m_group = group;
    m_type = type;
    m_isInstance = isInstance;
    m_line = line;
 }
Пример #23
0
        public static void BindDefinitionsToCategories(Document doc,
                                                       Application app,
                                                       List <Definition> defList,
                                                       List <Category> catList,
                                                       BuiltInParameterGroup bipGroup,
                                                       bool isInstance)
        {
            // restart variables to 0.
            failNamesList.Clear();
            countSuccess = 0;
            namesSuccess.Clear();
            instanceOrType = isInstance == true ? instanceOrType = "Instance" : instanceOrType = "Type";

            // category set
            CategorySet catSet = app.Create.NewCategorySet();

            foreach (Category cat in catList)
            {
                catSet.Insert(cat);
            }

            using (TransactionGroup tg = new TransactionGroup(doc, "Load Shared Parameters"))
            {
                tg.Start();
                foreach (Definition def in defList)
                {
                    using (Transaction t = new Transaction(doc, "Add parameter Binding: " + def.Name))
                    {
                        t.Start();
                        try
                        {
                            // is Family?
                            if (doc.IsFamilyDocument == true)
                            {
                                try
                                {
                                    ExternalDefinition extDef = def as ExternalDefinition;
                                    FamilyManager      famMan = doc.FamilyManager;
                                    famMan.AddParameter(extDef, bipGroup, isInstance);

                                    countSuccess += 1;
                                    namesSuccess.Add(def.Name);
                                }
                                catch (Exception e)
                                {
                                    failNamesList.Add(def.Name + " (" + e.Message + ")");
                                }
                            }
                            // is project document
                            else
                            {
                                if (isInstance == true) // instance parameter
                                {
                                    ExternalDefinition extDef = def as ExternalDefinition;
                                    InstanceBinding    bind   = app.Create.NewInstanceBinding(catSet);
                                    doc.ParameterBindings.Insert(extDef, bind, bipGroup);

                                    countSuccess += 1;
                                    namesSuccess.Add(def.Name);
                                }
                                else // type parameter
                                {
                                    TypeBinding bind = app.Create.NewTypeBinding(catSet);
                                    doc.ParameterBindings.Insert(def, bind, bipGroup);

                                    countSuccess += 1;
                                    namesSuccess.Add(def.Name);
                                }
                            }
                            t.Commit();
                        }
                        catch (Exception e)
                        {
                            failNamesList.Add(def.Name + " (" + e.Message + ")");
                        }
                    }
                }
                tg.Assimilate();
            }
        }
Пример #24
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static Definition ProjectParameter(Document document, string parameterName, ParameterType parameterType, BuiltInParameterGroup parameterGroup, bool instance, IEnumerable <Category> categories)
        {
            // Inspired by https://github.com/DynamoDS/DynamoRevit/blob/master/src/Libraries/RevitNodes/Elements/Parameter.cs

            if (categories != null && !categories.Any())
            {
                BH.Engine.Reflection.Compute.RecordError($"Parameter {parameterName} of type {LabelUtils.GetLabelFor(parameterType)} could not be created because no category bindings were provided.");
                return(null);
            }

            // Look for existing parameter definition
            bool bindings = false;
            IEnumerable <Definition> existingDefs = new FilteredElementCollector(document).OfClass(typeof(SharedParameterElement)).Cast <SharedParameterElement>().Select(x => x.GetDefinition());
            Definition def = existingDefs.FirstOrDefault(x => x.Name == parameterName && x.ParameterGroup == parameterGroup);

            if (def != null)
            {
                if (document.ParameterBindings.Contains(def))
                {
                    BH.Engine.Reflection.Compute.RecordWarning($"Parameter {parameterName} already exists in group {LabelUtils.GetLabelFor(parameterGroup)}. It already has category bindings, they were not updated - please make sure they are correct.");
                    bindings = true;
                }
                else
                {
                    BH.Engine.Reflection.Compute.RecordWarning($"Parameter {parameterName} already exists in group {LabelUtils.GetLabelFor(parameterGroup)}. It did not have any category bindings, so input bindings were applied.");
                }
            }
            else
            {
                // buffer the current shared parameter file name and apply a new empty parameter file instead
                string sharedParameterFile     = document.Application.SharedParametersFilename;
                string tempSharedParameterFile = System.IO.Path.GetTempFileName() + ".txt";
                using (System.IO.File.Create(tempSharedParameterFile)) { }
                document.Application.SharedParametersFilename = tempSharedParameterFile;

                // Create a new shared parameter, since the file is empty everything has to be created from scratch
                def = document.Application.OpenSharedParameterFile()
                      .Groups.Create("TempParameterGroup").Definitions.Create(
                    new ExternalDefinitionCreationOptions(parameterName, parameterType)) as ExternalDefinition;

                // apply old shared parameter file
                document.Application.SharedParametersFilename = sharedParameterFile;

                // delete temp shared parameter file
                System.IO.File.Delete(tempSharedParameterFile);
            }

            if (!bindings)
            {
                // Apply instance or type binding
                CategorySet paramCategories = (categories == null) ? document.CategoriesWithBoundParameters() : Create.CategorySet(document, categories);

                Binding bin = (instance) ?
                              (Binding)document.Application.Create.NewInstanceBinding(paramCategories) :
                              (Binding)document.Application.Create.NewTypeBinding(paramCategories);

                document.ParameterBindings.Insert(def, bin, parameterGroup);
            }

            return(def);
        }
Пример #25
0
 /// <summary>
 /// Tries to convert <see cref="BuiltInParameterGroup"/> value to a human-readable English label.
 /// </summary>
 /// <param name="builtInParameterGroup">Built in parameter group value.</param>
 /// <param name="builtInParameterGroupString">Human-readable English label for the given <see cref="BuiltInParameterGroup"/> value.</param>
 /// <returns></returns>
 public static bool ToEnglishLabel(this BuiltInParameterGroup builtInParameterGroup, out string builtInParameterGroupString)
 {
     return(_builtInParameterGroup.TryGetValue(builtInParameterGroup, out builtInParameterGroupString));
 }
Пример #26
0
        /// <summary>
        /// Method that finds the existing shared parameter and binds a new project parameter
        /// </summary>
        /// <param name="name"></param>
        /// <param name="cats"></param>
        /// <param name="group"></param>
        /// <param name="inst"></param>
        static public void CreateProjParamFromExistSharedParam(string name, CategorySet cats, BuiltInParameterGroup group, bool inst)
        {
            try
            {
                DefinitionFile defFile = EADocumentData.App.OpenSharedParameterFile();
                if (defFile == null)
                {
                    throw new FileReadFailedException("No SharedParameter File!");
                }

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

                ExternalDefinition def = v.First();

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

                BindingMap map = (new UIApplication(EADocumentData.App)).ActiveUIDocument.Document.ParameterBindings;
                map.Insert(def, binding, group);
            }
            catch (InvalidNameException ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
            catch (FileReadFailedException ex)
            {
                TaskDialog.Show("Error", ex.Message);
            }
        }
Пример #27
0
        private bool CreateSharedParameter(string paramName, ParameterType paramType, BuiltInParameterGroup pramGroup)
        {
            var created = false;

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

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

                        var instanceBinding = m_app.Application.Create.NewInstanceBinding(categorySet);
                        var bindingMap      = m_doc.ParameterBindings;
                        var instanceBindOK  = bindingMap.Insert(definition, instanceBinding, pramGroup);
                        trans.Commit();
                        created = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not create the Ceiling Height parametert." + paramName + "\n" + ex.Message, "CeilingHeightUtil : CreateSharedParameter", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    trans.RollBack();
                    created = false;
                }
            }
            return(created);
        }
Пример #28
0
        public static bool AddSharedParameterByDefaulGroupName(Document doc, string sharedParameterFile, string groupName, string parameterName, Category newCategory, bool isInstance, BuiltInParameterGroup parameterGroup)
        {
            doc.Application.SharedParametersFilename = sharedParameterFile;
            DefinitionFile   definitionFile = doc.Application.OpenSharedParameterFile();
            DefinitionGroups groups         = definitionFile.Groups;
            DefinitionGroup  group          = groups.get_Item(groupName);

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

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

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

            return(result);
        }
Пример #29
0
        public bool BindSharedParameters()
        {
            if (File.Exists(m_sharedFilePath) &&
                null == m_sharedFile)
            {
                MessageBox.Show("SharedParameter.txt has an invalid format.");
                return(false);
            }

            foreach (DefinitionGroup group in m_sharedFile.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
                    {
                        if (def.OwnerGroup.Name == "Dimensions")
                        {
                            bpg = BuiltInParameterGroup.PG_GEOMETRY;
                        }
                        else if (def.OwnerGroup.Name == "Electrical")
                        {
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL;
                        }
                        else if (def.OwnerGroup.Name == "Identity Data")
                        {
                            bpg = BuiltInParameterGroup.PG_IDENTITY_DATA;
                        }
                        else if (def.OwnerGroup.Name == "Electrical - Loads")
                        {
                            bpg = BuiltInParameterGroup.PG_ELECTRICAL_LOADS;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical - Air Flow")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_AIRFLOW;
                        }
                        else if (def.OwnerGroup.Name == "Energy Analysis")
                        {
                            bpg = BuiltInParameterGroup.PG_ENERGY_ANALYSIS;
                        }
                        else if (def.OwnerGroup.Name == "Mechanical - Loads")
                        {
                            bpg = BuiltInParameterGroup.PG_MECHANICAL_LOADS;
                        }
                        else if (def.OwnerGroup.Name == "Structural")
                        {
                            bpg = BuiltInParameterGroup.PG_STRUCTURAL;
                        }
                        else if (def.OwnerGroup.Name == "Plumbing")
                        {
                            bpg = BuiltInParameterGroup.PG_PLUMBING;
                        }
                        else if (def.OwnerGroup.Name == "Green Building Properties")
                        {
                            bpg = BuiltInParameterGroup.PG_GREEN_BUILDING;
                        }
                        else if (def.OwnerGroup.Name == "Materials and Finishes")
                        {
                            bpg = BuiltInParameterGroup.PG_MATERIALS;
                        }
                        else if (def.OwnerGroup.Name == "Other")
                        {
                            bpg = BuiltInParameterGroup.INVALID;
                        }
                        else if (def.OwnerGroup.Name == "Construction")
                        {
                            bpg = BuiltInParameterGroup.PG_CONSTRUCTION;
                        }
                        else
                        {
                            bpg = BuiltInParameterGroup.INVALID;
                        }

                        m_manager.AddParameter(def, bpg, true);
                    }
                    catch (System.Exception e)
                    {
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
            }
            return(true);
        }
Пример #30
0
 private int sortByLabel(BuiltInParameterGroup p1, BuiltInParameterGroup p2)
 {
     // Dim a As String = LabelUtils.GetLabelFor(p1)
     //   JerkHub.Ptr2Debug.addToDebug("Compare: " & LabelUtils.GetLabelFor(p1) & " : " & LabelUtils.GetLabelFor(p2))
     return(String.Compare(LabelUtils.GetLabelFor(p1), LabelUtils.GetLabelFor(p2), StringComparison.Ordinal));
 }
Пример #31
0
        /// <summary>
        /// load family parameters from the text file
        /// </summary>
        /// <returns>
        /// return true if succeeded; otherwise false
        /// </returns>
        private bool LoadFamilyParameterFromFile(out bool exist)
        {
            exist = true;
            // step 1: find the file "FamilyParameter.txt" and open it
            string fileName = m_assemblyPath + "\\FamilyParameter.txt";

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

            FileStream   file   = null;
            StreamReader reader = null;

            try
            {
                file   = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                reader = new StreamReader(file);

                // step 2: read each line, if the line records the family parameter data, store it
                // record the content of the current line
                string line;
                // record the row number of the current line
                int lineNumber = 0;
                while (null != (line = reader.ReadLine()))
                {
                    ++lineNumber;
                    // step 2.1: verify the line
                    // check whether the line is blank line (contains only whitespaces)
                    Match match = Regex.Match(line, @"^\s*$");
                    if (true == match.Success)
                    {
                        continue;
                    }

                    // check whether the line starts from "#" or "*" (comment line)
                    match = Regex.Match(line, @"\s*['#''*'].*");
                    if (true == match.Success)
                    {
                        continue;
                    }

                    // step 2.2: get the parameter data
                    // it's a valid line (has the format of "paramName   paramGroup    paramType    isInstance", separate by tab or by spaces)
                    // split the line to an array containing parameter items (format of string[] {"paramName", "paramGroup", "paramType", "isInstance"})
                    string[] lineData = Regex.Split(line, @"\s+");
                    // check whether the array has blank items (containing only spaces)
                    List <string> values = new List <string>();
                    foreach (string data in lineData)
                    {
                        match = Regex.Match(data, @"^\s*$");
                        if (true == match.Success)
                        {
                            continue;
                        }

                        values.Add(data);
                    }

                    // verify the parameter items (should have 4 items exactly: paramName, paramGroup, paramType and isInstance)
                    if (4 != values.Count)
                    {
                        MessageManager.MessageBuff.Append("Loading family parameter data from \"FamilyParam.txt\".");
                        MessageManager.MessageBuff.Append("Line [\"" + line + "]\"" + "doesn't follow the valid format.\n");
                        return(false);
                    }

                    // get the paramName
                    string paramName = values[0];
                    // get the paramGroup
                    string groupString = values[1];
                    // in case the groupString is format of "BuiltInParameterGroup.PG_Text", need to remove the "BuiltInParameterGroup.",
                    // keep the "PG_Text" only
                    int index = -1;
                    if (0 <= (index = groupString.ToLower().IndexOf("builtinparametergroup")))
                    {
                        // why +1? need to remove the "." after "builtinparametergroup"
                        groupString = groupString.Substring(index + 1 + "builtinparametergroup".Length);
                    }
                    BuiltInParameterGroup paramGroup = (BuiltInParameterGroup)Enum.Parse(typeof(BuiltInParameterGroup), groupString);

                    // get the paramType
                    string typeString = values[2];
                    if (0 <= (index = typeString.ToLower().IndexOf("parametertype")))
                    {
                        // why +1? need to remove the "." after "builtinparametergroup"
                        typeString = typeString.Substring(index + 1 + "parametertype".Length);
                    }
                    ParameterType paramType = (ParameterType)Enum.Parse(typeof(ParameterType), typeString);
                    // get data "isInstance"
                    string isInstanceString = values[3];
                    bool   isInstance       = Convert.ToBoolean(isInstanceString);

                    // step 2.3: store the parameter fetched, check for exclusiveness (as the names of parameters should keep unique)
                    FamilyParam param = new FamilyParam(paramName, paramGroup, paramType, isInstance, lineNumber);
                    // the family parameter with the same name has already been stored to the dictionary, raise an error
                    if (m_familyParams.ContainsKey(paramName))
                    {
                        FamilyParam duplicatedParam = m_familyParams[paramName];
                        string      warning         = "Line " + param.Line + "has a duplicate parameter name with Line " + duplicatedParam.Line + "\n";
                        MessageManager.MessageBuff.Append(warning);
                        continue;
                    }
                    m_familyParams.Add(paramName, param);
                }
            }
            catch (System.Exception e)
            {
                MessageManager.MessageBuff.AppendLine(e.Message);
                return(false);
            }
            finally
            {
                if (null != reader)
                {
                    reader.Close();
                }
                if (null != file)
                {
                    file.Close();
                }
            }

            return(true);
        }
Пример #32
0
        private static void CreateProjectParam(Autodesk.Revit.ApplicationServices.Application app,
                                               string name, ParameterType type, bool visible, CategorySet catSet, BuiltInParameterGroup group, bool inst)
        {
            // Check whether the parameter has already been added.
            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;
            DefinitionBindingMapIterator itr = map.ForwardIterator();

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

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

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

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

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

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

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

            map.Insert(def, binding);
        }
        /// <summary>
        /// Gets double value from parameter of an element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="group">Optional property group to limit search to.</param>
        /// <param name="propertyName">The property name.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when element is null.</exception>
        /// <exception cref="System.ArgumentException">Thrown when propertyName is null or empty.</exception>
        /// <returns>The parameter, or null if not found.</returns>
        public static Parameter GetDoubleValueFromElement(Element element, BuiltInParameterGroup? group, string propertyName, out double propertyValue)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            if (String.IsNullOrEmpty(propertyName))
                throw new ArgumentException("It is null or empty.", "propertyName");

            propertyValue = 0.0;

            Parameter parameter = GetParameterFromName(element.Id, group, propertyName);

            if (parameter != null && parameter.HasValue)
            {
                switch (parameter.StorageType)
                {
                    case StorageType.Double:
                        propertyValue = parameter.AsDouble();
                        return parameter;
                    case StorageType.Integer:
                        propertyValue = parameter.AsInteger();
                        return parameter;
                    case StorageType.String:
                        return Double.TryParse(parameter.AsString(), out propertyValue) ? parameter : null;
                }
            }

            return null;
        }
Пример #34
0
        public Result Execute(ExternalCommandData commandData,
                              ref string message,
                              ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            // Launches the application window (WPF) for user input
            OpenRFA_WPF_CS.MainWindow appDialog = new MainWindow();
            appDialog.ShowDialog();


            {
                // Only executes if the user clicked "OK" button
                if (appDialog.DialogResult.HasValue && appDialog.DialogResult.Value)
                {
                    // Opens configuration window
                    OpenRFA_WPF_CS.ConfigureImport confDialog = new ConfigureImport();
                    confDialog.ShowDialog();

                    using (Transaction trans = new Transaction(doc, "AddParams"))
                    {
                        // Save list of parameters from MainWindow
                        ImportProcess.ParamCache = MainWindow.paramsOut;

                        // Check if configuration options have been saved
                        if (confDialog.DialogResult.HasValue && confDialog.DialogResult.Value)
                        {
                            // Test text for showing if datatable has been updated.
                            StringBuilder sb = new StringBuilder();
                            sb.Append("Updated datatable: \n");
                            foreach (DataRow dr in ConfigureImport.dtConfig.Rows)
                            {
                                sb.Append(dr[0] + ", " + dr[1] + "," + dr[2] + "\n");
                            }
                            MessageBox.Show(sb.ToString());

                            trans.Start();

                            // Set current shared parameters file
                            app.SharedParametersFilename = LocalFiles.tempDefinitionsFile;
                            defFile = app.OpenSharedParameterFile();

                            // Adds shared parameters to family
                            // TODO: Pass a list of BuiltInParameterGroup (currently only a placeholder) for overload
                            //SharedParameter.ImportParameterToFamily(doc, defFile, BuiltInParameterGroup.PG_MECHANICAL);

                            foreach (DataRow _row in ConfigureImport.dtConfig.Rows)
                            {
                                // Check if configuration is set to instance.
                                // TODO: Turn this into a method.
                                bool _instance = false;
                                if (_row[2].ToString() == "Instance")
                                {
                                    _instance = true;
                                }
                                else
                                {
                                    _instance = false;
                                }

                                // Get BuiltInParameterGroup by name
                                BuiltInParameterGroup _bipGroup = new BuiltInParameterGroup();
                                _bipGroup = SPBuiltInGroup.GetByName(_row[1].ToString());

                                // Get BIPG using the BuiltinParameterGroupLookup Class
                                var lookup = new BuiltInParameterGroupLookup();
                                BuiltInParameterGroup _selectedGroup = lookup[_row[1].ToString()];

                                // Write shared parameter to family
                                SharedParameter.ImportParameterToFamily(doc, defFile, _row, _selectedGroup, _instance);
                            }

                            trans.Commit();
                        }
                        else
                        {
                            MessageBox.Show("Operation canceled.");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Operation canceled.");
                }
            }

            // Clear DataTables. TODO: Turn this into a method.
            ConfigureImport.dtConfig.Clear();
            ImportProcess.RemoveColumns(ConfigureImport.dtConfig);

            return(Result.Succeeded);
        }
        /// <summary>
        /// Gets the parameter by name from an element for a specific parameter group.
        /// </summary>
        /// <param name="elemId">The element id.</param>
        /// <param name="group">The optional parameter group.</param>
        /// <param name="propertyName">The property name.</param>
        /// <returns>The Parameter.</returns>
        static Parameter GetParameterFromName(ElementId elemId, BuiltInParameterGroup? group, string propertyName)
        {
            if (!m_IFCParameters.ContainsKey(elemId))
                CacheParametersForElement(elemId);

            return group.HasValue ?
                getParameterByNameFromCache(elemId, group.Value, propertyName) :
                getParameterByNameFromCache(elemId, propertyName);
        }
Пример #36
0
        public void AddParametersToProject(Document doc, Autodesk.Revit.ApplicationServices.Application app)
        {
            Dictionary <string, BuiltInParameterGroup> builtInParameterGroupDictionary = new SharedParametersLibrary(doc, app).BuiltInParameterGroupDictionary(doc);
            SortedList <string, Category> parameterCategoryList = new SharedParametersLibrary(doc, app).ParameterCategoryList(doc);

            selectedGroup = GroupParameterUnderComboBox.SelectedItem;
            string selectedGroupName = selectedGroup.ToString();

            definitionGroup = GroupSelectComboBox.SelectedItem;
            string definitionGroupName = definitionGroup.ToString();

            BuiltInParameterGroup builtInParameterGroup = builtInParameterGroupDictionary[selectedGroupName];

            SortedList <string, ExternalDefinition> sharedParameterList = new SharedParametersLibrary(doc, app).GetSharedParameterList(definitionGroupName);

            CategorySet categoryset = app.Create.NewCategorySet();

            foreach (string category in CategoryCheckList.CheckedItems)
            {
                categoryset.Insert(parameterCategoryList[category]);
            }

            // existing shared parameter list
            List <string>            collectorList            = new List <string>();
            List <string>            existingParameterList    = new List <string>();
            List <string>            nonExistingParameterList = new List <string>();
            FilteredElementCollector parameterCollector       = new FilteredElementCollector(doc);

            parameterCollector.OfClass(typeof(SharedParameterElement));

            foreach (var e in parameterCollector)
            {
                collectorList.Add(e.Name.ToString());
            }

            foreach (string parameter in ParameterList.SelectedItems)
            {
                if (collectorList.Contains(parameter))
                {
                    existingParameterList.Add(parameter);
                }
                else
                {
                    nonExistingParameterList.Add(parameter);
                }
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Add Selected Shared Parameters");

                foreach (string selectedParameter in nonExistingParameterList)
                {
                    if ((sharedParameterList.ContainsKey(selectedParameter)) && (TypeCheck.Checked))
                    {
                        ExternalDefinition externalDefinition =
                            new SharedParametersLibrary(doc, app).ExternalDefinitionExtractor(selectedParameter, sharedParameterList);
                        TypeBinding newBinding = app.Create.NewTypeBinding(categoryset);
                        doc.ParameterBindings.Insert(externalDefinition, newBinding, builtInParameterGroup);
                    }
                    else if ((sharedParameterList.ContainsKey(selectedParameter)) && (InstanceCheck.Checked))
                    {
                        ExternalDefinition externalDefinition =
                            new SharedParametersLibrary(doc, app).ExternalDefinitionExtractor(selectedParameter, sharedParameterList);
                        InstanceBinding newBinding = app.Create.NewInstanceBinding(categoryset);
                        doc.ParameterBindings.Insert(externalDefinition, newBinding, builtInParameterGroup);
                    }
                    else
                    {
                    }
                }
                foreach (string selectedParameter in existingParameterList)
                {
                    if ((sharedParameterList.ContainsKey(selectedParameter)) && (TypeCheck.Checked))
                    {
                        ExternalDefinition externalDefinition =
                            new SharedParametersLibrary(doc, app).ExternalDefinitionExtractor(selectedParameter, sharedParameterList);
                        TypeBinding newBinding = app.Create.NewTypeBinding(categoryset);
                        doc.ParameterBindings.ReInsert(externalDefinition, newBinding, builtInParameterGroup);
                    }
                    else if ((sharedParameterList.ContainsKey(selectedParameter)) && (InstanceCheck.Checked))
                    {
                        ExternalDefinition externalDefinition =
                            new SharedParametersLibrary(doc, app).ExternalDefinitionExtractor(selectedParameter, sharedParameterList);
                        InstanceBinding newBinding = app.Create.NewInstanceBinding(categoryset);
                        doc.ParameterBindings.ReInsert(externalDefinition, newBinding, builtInParameterGroup);
                    }
                    else
                    {
                    }
                }
                tx.Commit();
            }
        }
Пример #37
0
        // Assumes outer transaction
        public static Parameter GetOrCreateElemSharedParam(
            Element elem,
            string paramName,
            string grpName,
            ParameterType paramType,
            bool visible,
            bool instanceBinding,
            bool userModifiable,
            Guid guid,
            bool useTempSharedParamFile,
            string tooltip = "",
            BuiltInParameterGroup uiGrp = BuiltInParameterGroup.INVALID,
            bool allowVaryBetweenGroups = true)
        {
            try
            {
                // Check if existing
                Parameter param = elem.LookupParameter(paramName);
                if (null != param)
                {
                    // NOTE: If you don't want forcefully setting
                    // the "old" instance params to
                    // allowVaryBetweenGroups =true,
                    // just comment the next 3 lines.
                    if (instanceBinding && allowVaryBetweenGroups)
                    {
                        SetInstanceParamVaryBetweenGroupsBehaviour(
                            elem.Document, guid, allowVaryBetweenGroups);
                    }
                    return(param);
                }

                // If here, need to create it (my custom
                // implementation and classes…)

                BindSharedParamResult res = BindSharedParam(
                    elem.Document, elem.Category, paramName, grpName,
                    paramType, visible, instanceBinding, userModifiable,
                    guid, useTempSharedParamFile, tooltip, uiGrp);

                if (res != BindSharedParamResult.eSuccessfullyBound &&
                    res != BindSharedParamResult.eAlreadyBound)
                {
                    return(null);
                }

                // Set AllowVaryBetweenGroups for NEW Instance
                // Binding Shared Param

                if (instanceBinding)
                {
                    SetInstanceParamVaryBetweenGroupsBehaviour(
                        elem.Document, guid, allowVaryBetweenGroups);
                }

                // If here, binding is OK and param seems to be
                // IMMEDIATELY available from the very same command

                return(elem.LookupParameter(paramName));
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(
                    string.Format(
                        "Error in getting or creating Element Param: {0}",
                        ex.Message));

                return(null);
            }
        }
Пример #38
0
        bool CreateKeyParameter(Category category, Document document, string parameterName, ParameterType parameterType, BuiltInParameterGroup parameterGroup, Guid guid)
        {
            Application application = document.Application;
            string      temShareDefinitionFilePath      = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"/temSharpParam.txt";
            string      originalShareDefinitionFilePath = application.SharedParametersFilename;

            if (File.Exists(temShareDefinitionFilePath))
            {
                File.Delete(temShareDefinitionFilePath);
            }
            FileStream fileStream = File.Create(temShareDefinitionFilePath);

            fileStream.Close();

            application.SharedParametersFilename = temShareDefinitionFilePath;
            DefinitionFile  definitionFile = application.OpenSharedParameterFile();
            DefinitionGroup shareParaGroup = definitionFile.Groups.Create("mySharePara");
            ExternalDefinitionCreationOptions definitionOpt = new ExternalDefinitionCreationOptions(parameterName, parameterType);

            if (guid != null)
            {
                definitionOpt.GUID = guid;
            }
            Definition definition = shareParaGroup.Definitions.Create(definitionOpt);

            CategorySet categorySet = new CategorySet();

            categorySet.Insert(category);
            bool result = document.ParameterBindings.Insert(definition, new InstanceBinding(categorySet), parameterGroup);

            if (!String.IsNullOrEmpty(originalShareDefinitionFilePath))
            {
                application.SharedParametersFilename = originalShareDefinitionFilePath;
            }
            File.Delete(temShareDefinitionFilePath);

            return(result);
        }
Пример #39
0
        static public bool AddSharedParameter(
            Document doc,
            string parameterName,
            BuiltInCategory[] categories,
            BuiltInParameterGroup group = BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES,
            bool isIntance = true
            )
        {
            // Проверка параметра на наличие
            List <bool> check = new List <bool>();

            foreach (BuiltInCategory cat in categories)
            {
                check.Add(IsParameterInProject(doc, parameterName, cat));
            }

            if (check.All(x => x == true))
            {
                return(true);
            }
            else
            {
                CategorySet catSet = doc.Application.Create.NewCategorySet();
                foreach (BuiltInCategory c in categories)
                {
                    catSet.Insert(doc.Settings.Categories.get_Item(c));
                }

                try
                {
                    doc.Application.SharedParametersFilename = sharedParameterFilePath;
                    DefinitionFile     spFile    = doc.Application.OpenSharedParameterFile();
                    ExternalDefinition sharedDef = null;
                    foreach (DefinitionGroup gr in spFile.Groups)
                    {
                        foreach (Definition def in gr.Definitions)
                        {
                            if (def.Name == parameterName)
                            {
                                sharedDef = (ExternalDefinition)def;
                            }
                        }
                    }
                    if (sharedDef == null)
                    {
                        TaskDialog.Show("Ошибка", String.Format("Параметр \"{0}\" отсутствует в файле общих параметров", parameterName));
                        return(false);
                    }

                    ElementBinding bind;
                    if (isIntance)
                    {
                        bind = doc.Application.Create.NewInstanceBinding(catSet);
                    }
                    else
                    {
                        bind = doc.Application.Create.NewTypeBinding(catSet);
                    }
                    bool result = doc.ParameterBindings.Insert(sharedDef, bind, group);
                    // Если параметр уже существует, но данная категория отсутствует в сете - обновляем сет
                    if (!result)
                    {
                        string realName = GetRealParameterName(doc, sharedDef);
                        bind = GetParameterBinding(doc, realName);
                        foreach (Category c in catSet)
                        {
                            bind.Categories.Insert(c);
                        }
                        bool result2 = doc.ParameterBindings.ReInsert(sharedDef, bind, group);
                        if (!result2)
                        {
                            TaskDialog.Show("Ошибка", String.Format("Произошла ошибка при редактировании привязок существующего параметра \"{0}\"", parameterName));
                            return(false);
                        }
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    TaskDialog td = new TaskDialog("Ошибка");
                    td.MainInstruction = String.Format("Произошла ошибка добавления общего параметра \"{0}\"", parameterName);
                    td.MainContent     = e.ToString();
                    td.Show();
                    return(false);
                }
            }
        }
        /// <summary>
        /// create project parameter
        /// source :http://spiderinnet.typepad.com/blog/2011/05/parameter-of-revit-api-31-create-project-parameter.html
        /// </summary>
        /// <param name="app">revit application</param>
        /// <param name="name">revit ui application</param>
        /// <param name="type">parameter type</param>
        /// <param name="cats">category set</param>
        /// <param name="group">parameter group</param>
        /// <param name="inst">is instance variable</param>
        public  void CreateProjectParameter(Application app, string name, ParameterType type,  CategorySet cats, BuiltInParameterGroup group, bool instance)
        {
    

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

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

            Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats);
            if (instance) binding = app.Create.NewInstanceBinding(cats);
            BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings;
            map.Insert(def, binding, group);
        }