public static bool CreateSharedProjectParameters(Document doc, string param, CategorySet catSet) { DefinitionFile sharedParamsFile = GetSharedParamsFile(doc); if (null == sharedParamsFile) { throw new Exception("Shared Paremeter file does not exist.\nSet or Create the project Shared Parameter file."); } DefinitionGroup sharedParamsGroup = GetCreateSharedParamsGroup(sharedParamsFile, "Group6Face"); Definition definition = GetCreateSharedParamsDefinition(sharedParamsGroup, ParameterType.Text, param, true); BindingMap bindMap = doc.ParameterBindings; Autodesk.Revit.DB.Binding binding = bindMap.get_Item(definition); bindMap.ReInsert(definition, binding); InstanceBinding instanceBinding = doc.Application.Create.NewInstanceBinding(catSet); try { if (!doc.ParameterBindings.Insert(definition, instanceBinding)) { doc.ParameterBindings.ReInsert(definition, instanceBinding); } return(true); } catch (Exception ex) { throw new Exception("Uneable to create parameter bindings.\n" + ex.Message); } }
public static void ExportParameters(Document doc, string path) { DefinitionFile existingDefFile = doc.Application.OpenSharedParameterFile(); // doc.Application.SharedParametersFilename = path; DefinitionFile tempDefFile = doc.Application.OpenSharedParameterFile(); // Manager the Exported group DefinitionGroup exported = null; var query = from dg in tempDefFile.Groups where dg.Name.Equals(doc.PathName + "-Exported") select dg; if (query.Count() == 0) { exported = tempDefFile.Groups.Create(doc.PathName + "-Exported"); } else { exported = query.First(); } // Iterate over the shared parameters in the document BindingMap bindingMap = doc.ParameterBindings; DefinitionBindingMapIterator it = bindingMap.ForwardIterator(); it.Reset(); while (it.MoveNext()) { InternalDefinition definition = it.Key as InternalDefinition; Autodesk.Revit.DB.Binding currBinding = bindingMap.get_Item(definition); // Corroborate that the current parameter has not been exported previously Definition existingDef = exported.Definitions .Where(d => (d.Name.Equals(definition.Name))).FirstOrDefault(); if (existingDef != null) { continue; } // unearth and assign the parameter's GUID SharedParameterElement sharedParamElem = doc.GetElement(definition.Id) as SharedParameterElement; if (sharedParamElem == null) { continue; } ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions(definition.Name, definition.ParameterType); options.GUID = sharedParamElem.GuidValue; Definition createdDefinition = exported.Definitions.Create(options); } }
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); }
public static IList <SharedParameter> GetSharedParameters(Document doc) { IList <SharedParameter> extSharedParams = new List <SharedParameter>(); BindingMap bindingMap = doc.ParameterBindings; DefinitionBindingMapIterator it = bindingMap.ForwardIterator(); it.Reset(); while (it.MoveNext()) { InternalDefinition definition = it.Key as InternalDefinition; Autodesk.Revit.DB.Binding currBinding = bindingMap.get_Item(definition); // unearth the parameter's GUID SharedParameterElement sharedParamElem = doc.GetElement(definition.Id) as SharedParameterElement; if (sharedParamElem == null) { continue; } SharedParameter sharedParam = new SharedParameter(definition.Name, definition.ParameterType, sharedParamElem.GuidValue, currBinding, definition.ParameterGroup); extSharedParams.Add(sharedParam); } return(extSharedParams); }
/// <summary> /// Create a project parameter /// </summary> /// <param name="app"></param> /// <param name="name"></param> /// <param name="type"></param> /// <param name="visible"></param> /// <param name="cats"></param> /// <param name="group"></param> /// <param name="inst"></param> public static void RawCreateProjectParameter(Autodesk.Revit.ApplicationServices.Application app, string name, ParameterType type, bool visible, CategorySet cats, BuiltInParameterGroup group, bool inst) { string oriFile = app.SharedParametersFilename; string tempFile = Path.GetTempFileName() + ".txt"; using (File.Create(tempFile)) { } app.SharedParametersFilename = tempFile; ExternalDefinitionCreationOptions externalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(name, type); ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions.Create(externalDefinitionCreationOptions) as ExternalDefinition; app.SharedParametersFilename = oriFile; File.Delete(tempFile); Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats); if (inst) { binding = app.Create.NewInstanceBinding(cats); } BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings; map.Insert(def, binding, group); }
private void TransactionCommit(Document doc, ExternalDefinition def, Autodesk.Revit.DB.Binding binding, BuiltInParameterGroup group) { using (Transaction transNew = new Transaction(doc, "Create project parameter")) { try { transNew.Start(); BindingMap map = doc.ParameterBindings; if (SelectParameters.OverwriteParam == true) { map.ReInsert(def, binding, group); } map.Insert(def, binding, group); } catch (Exception e) { transNew.RollBack(); MessageBox.Show(e.ToString()); } transNew.Commit(); } }
public string myMethod_BindParameters(string path, bool IsTypeParameter) { UIDocument uidoc = myWindow1.commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; string myStringSharedParameterFileName = ""; if (uidoc.Application.Application.SharedParametersFilename != null) { myStringSharedParameterFileName = uidoc.Application.Application.SharedParametersFilename; //Q:\Revit Revit Revit\Template 2018\PRL_Parameters.txt } uidoc.Application.Application.SharedParametersFilename = path; DefinitionFile myDefinitionFile = uidoc.Application.Application.OpenSharedParameterFile(); if (myStringSharedParameterFileName != "") { uidoc.Application.Application.SharedParametersFilename = myStringSharedParameterFileName; } if (myDefinitionFile == null) { DatabaseMethods.writeDebug(path + Environment.NewLine + Environment.NewLine + "File does not exist OR cannot be opened.", true); return(""); } CategorySet catSet = uidoc.Application.Application.Create.NewCategorySet(); foreach (Category myCatttt in doc.Settings.Categories) { if (myCatttt.AllowsBoundParameters) { catSet.Insert(myCatttt); } } string myStringCollectup = ""; DefinitionGroup group = myDefinitionFile.Groups.get_Item("Default"); foreach (Definition myDefinition in group.Definitions) { myStringCollectup = myStringCollectup + " • " + myDefinition.Name; Binding binding = IsTypeParameter ? uidoc.Application.Application.Create.NewTypeBinding(catSet) as Binding : uidoc.Application.Application.Create.NewInstanceBinding(catSet) as Binding; using (Transaction tx = new Transaction(doc)) { tx.Start("EE07_Part1_Binding"); doc.ParameterBindings.Insert(myDefinition, binding, BuiltInParameterGroup.PG_IDENTITY_DATA); tx.Commit(); } } myStringCollectup = (IsTypeParameter ? "Type" : "Instance") + " parameters added to all categories:" + Environment.NewLine + myStringCollectup; return(myStringCollectup); }
void AddParameterToProject(Document doc, CategorySet cats, BuiltInParameterGroup group, string parameterName) { App.Application.SharedParametersFilename = StartForm.SPFPath; ExternalDefinition def = App.Application.OpenSharedParameterFile().Groups. get_Item(SelectParameters.SelectedGroupName).Definitions.get_Item(parameterName) as ExternalDefinition; Autodesk.Revit.DB.Binding binding = App.Application.Create.NewTypeBinding(cats); TransactionCommit(doc, def, binding, group); }
/// <summary> /// Add Shared GID Parameter to active Document /// </summary> /// <param name="document"></param> /// <returns>returns if operation succeeded</returns> public static bool GrevitAddSharedParameter(this Document document) { try { string parameterName = "GID"; ParameterType parameterType = ParameterType.Text; string sharedParameterFile = document.Application.SharedParametersFilename; string tempSharedParameterFile = System.IO.Path.GetTempFileName() + ".txt"; using (System.IO.File.Create(tempSharedParameterFile)) { } document.Application.SharedParametersFilename = tempSharedParameterFile; // Create a new Category Set to apply the parameter to CategorySet categories = document.Application.Create.NewCategorySet(); // Walk thru all categories and add them if they allow bound parameters foreach (Category cat in document.Settings.Categories) { if (cat.AllowsBoundParameters) { categories.Insert(cat); } } // Create and External Definition in a Group called Grevit and a Parameter called GID #if (!Revit2015) ExternalDefinition def = document.Application.OpenSharedParameterFile().Groups.Create("Grevit").Definitions.Create(new ExternalDefinitionCreationOptions(parameterName, parameterType)) as ExternalDefinition; #else ExternalDefinition def = document.Application.OpenSharedParameterFile().Groups.Create("Grevit").Definitions.Create(new ExternalDefinitonCreationOptions(parameterName, parameterType)) as ExternalDefinition; #endif document.Application.SharedParametersFilename = sharedParameterFile; System.IO.File.Delete(tempSharedParameterFile); // Apply the Binding to almost all Categories Autodesk.Revit.DB.Binding bin = document.Application.Create.NewInstanceBinding(categories); BindingMap map = (new UIApplication(document.Application)).ActiveUIDocument.Document.ParameterBindings; map.Insert(def, bin, BuiltInParameterGroup.PG_DATA); return(true); } catch (Exception e) { return(false); } }
/// <summary> /// Create project parameter from existing shared parameter /// </summary> /// <param name="app"></param> /// <param name="name"></param> /// <param name="cats"></param> /// <param name="group"></param> /// <param name="inst"></param> public static void RawCreateProjectParameterFromExistingSharedParameter(Autodesk.Revit.ApplicationServices.Application app, string name, CategorySet cats, BuiltInParameterGroup group, bool inst) { //Location of the shared parameters string oriFile = app.SharedParametersFilename; //My Documents var newpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //Create txt inside my documents Extract("RenumberParts", newpath, "Resources", "SP_RenumberParts.txt"); //Create variable with the location on SP.txt inside my documents string tempFile = newpath + @"\SP_RenumberParts.txt"; //Change the location of the shared parameters for the SP location app.SharedParametersFilename = tempFile; DefinitionFile defFile = app.OpenSharedParameterFile(); var v = (from DefinitionGroup dg in defFile.Groups from ExternalDefinition d in dg.Definitions where d.Name == name select d); if (v == null || v.Count() < 1) { throw new Exception("Invalid Name Input!wwwww"); } ExternalDefinition def = v.First(); //Place original SP file app.SharedParametersFilename = oriFile; //Delete SP temporary file System.IO.File.Delete(tempFile); Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats); if (inst) { binding = app.Create.NewInstanceBinding(cats); } BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings; map.Insert(def, binding, group); }
public static void RawCreateProjectParameterFromNewSharedParameter(RvtApplication app, string defGroup, string name, ParameterType type, bool visible, CategorySet cats, BuiltInParameterGroup paramGroup, bool inst) { DefinitionFile defFile = app.OpenSharedParameterFile(); if (defFile == null) { throw new Exception("No SharedParameter File!"); } //ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create(defGroup).Definitions.Create(name, type, visible) as ExternalDefinition; ExternalDefinition def = app.OpenSharedParameterFile().Groups.Create(defGroup).Definitions.Create(new ExternalDefinitionCreationOptions(name, type)) as ExternalDefinition; Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(cats); if (inst) { binding = app.Create.NewInstanceBinding(cats); } BindingMap map = (new UIApplication(app)).ActiveUIDocument.Document.ParameterBindings; map.Insert(def, binding, paramGroup); }
/// <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); } }
public Result Generate(ExternalCommandData commandData, ref string message) { Document document = commandData.Application.ActiveUIDocument.Document; System.Text.StringBuilder log = new System.Text.StringBuilder(); Transaction trans = new Transaction(document, "Generate PCF parameters binding"); trans.Start(); try { DefinitionFile sharedParamFile = document.Application.OpenSharedParameterFile(); if (sharedParamFile == null) { string ExecutingAssemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string OriginalFile = document.Application.SharedParametersFilename; string CustomFile = ExecutingAssemblyDirectory + "\\PCFSharedParameters.txt"; using (File.Create(CustomFile)) { } document.Application.SharedParametersFilename = CustomFile; sharedParamFile = document.Application.OpenSharedParameterFile(); if (sharedParamFile == null) { throw new Exception("Fail: Create Shared Paramters for PCF Exporting."); } } string groupname = "PCF_SharedParameter"; DefinitionGroup grp = sharedParamFile.Groups.FirstOrDefault(g => g.Name == groupname); if (grp == null) { grp = sharedParamFile.Groups.Create(groupname); } CategorySet categories = document.Application.Create.NewCategorySet(); categories.Insert(document.Settings.Categories.get_Item(BuiltInCategory.OST_PipingSystem)); categories.Insert(document.Settings.Categories.get_Item(BuiltInCategory.OST_PipeCurves)); categories.Insert(document.Settings.Categories.get_Item(BuiltInCategory.OST_PipeFitting)); categories.Insert(document.Settings.Categories.get_Item(BuiltInCategory.OST_PipeAccessory)); IList <Definition> defs = new List <Definition>(); foreach (RevitParam.ParameterDefinition pd in RevitParam.ParamterList.Values) { if (!this.isParamExist(grp.Definitions, pd)) { ExternalDefinitionCreationOptions edco = new ExternalDefinitionCreationOptions(pd.Name, pd.Type); edco.GUID = pd.Id; defs.Add(grp.Definitions.Create(edco)); } else { defs.Add(grp.Definitions.get_Item(pd.Name)); } } BindingMap bindingMap = document.ParameterBindings; Autodesk.Revit.DB.Binding binding = document.Application.Create.NewInstanceBinding(categories); foreach (Definition def in defs) { if (bindingMap.Contains(def)) { log.Append("Parameter " + def.Name + " already exists.\n"); } else { bindingMap.Insert(def, binding, BuiltInParameterGroup.PG_ANALYTICAL_MODEL); if (bindingMap.Contains(def)) { log.Append("Parameter " + def.Name + " added to project.\n"); } else { log.Append("Creation of parameter " + def.Name + " failed for some reason.\n"); } } } trans.Commit(); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { trans.RollBack(); message = ex.Message; return(Result.Failed); } MessageBox.Show(log.ToString()); return(Result.Succeeded); }
/// <summary> /// 将外部共享参数创建为项目参数,并将其绑定到指定的类别 /// </summary> /// <param name="transDoc"> bindingMap.Insert 与 bindingMap.ReInsert 方法必须在事务内才能执行</param> /// <param name="doc"></param> /// <param name="facenCategoryId"> 面层对象所属的类别 </param> public void BindParametersToCategory(Transaction transDoc, Document doc, ElementId facenCategoryId) { // 打开共享文件 Autodesk.Revit.ApplicationServices.Application app = doc.Application; string OriginalSharedFileName = app.SharedParametersFilename; // Revit程序中,原来的共享文件路径 app.SharedParametersFilename = ProjectPath.SharedParameters; // 设置Revit的共享参数文件 DefinitionFile myDefinitionFile = app.OpenSharedParameterFile(); // 如果没有找到对应的文件,则打开时不会报错,而是直接返回Nothing // app.SharedParametersFilename = OriginalSharedFileName; // 将Revit程序中的共享文件路径还原,以隐藏插件程序中的共享参数文件。 // create a new group in the shared parameters file DefinitionGroup myGroup = myDefinitionFile.Groups.get_Item(FaceWallParameters.sp_Group_Face); // 提取此共享参数组中的每一个参数,并赋值给指定的类别 ExternalDefinition exdef_FaceIdTag = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_FaceIdTag); ExternalDefinition exdef_FaceType = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_FaceType); ExternalDefinition exdef_Volumn = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_Volumn); ExternalDefinition exdef_Area = (ExternalDefinition)myGroup.Definitions.get_Item(FaceWallParameters.sp_Area); // BindingMap bindingMap = doc.ParameterBindings; Category myCategory = Category.GetCategory(doc, facenCategoryId); // --------------------------------------------------------------------------------------------------------- // 判断指定的类别中是否绑定有此 "面层标识 FaceIdTag" 参数 bool faceParaHasInsertedIntoThatCategory = false; bool parameterHasBeenAddedToProject = false; if (bindingMap.Contains(exdef_FaceIdTag)) { Autodesk.Revit.DB.Binding parameterBinding = doc.ParameterBindings.get_Item(exdef_FaceIdTag); parameterHasBeenAddedToProject = true; if (parameterBinding is InstanceBinding) { // 外部共享参数 exdef_FaceIdTag 在此文档中 绑定到了哪些类别 CategorySet bindedCategories = ((InstanceBinding)parameterBinding).Categories; if (bindedCategories.Contains(myCategory)) { faceParaHasInsertedIntoThatCategory = true; } } } // --------------------------------------------------------------------------------------------------------- // 如果此参数"面层标识 FaceIdTag"还没有被添加到项目参数中,则先将用 Insert 其进行添加 if (!parameterHasBeenAddedToProject) { // 在“项目参数”中添加此参数,并为其指定一个绑定的类别。 CategorySet myCategories = app.Create.NewCategorySet(); myCategories.Insert(myCategory); //Create an instance of InstanceBinding InstanceBinding instanceBinding = app.Create.NewInstanceBinding(myCategories); // Get the BingdingMap of current document. // Bind the definitions to the document bindingMap.Insert(exdef_FaceIdTag, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); // 此 Insert 操作必须在事务开启后才能执行 bindingMap.Insert(exdef_FaceType, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); bindingMap.Insert(exdef_Volumn, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); bindingMap.Insert(exdef_Area, instanceBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); } // --------------------------------------------------------------------------------------------------------- // 如果"面层标识 FaceIdTag" 参数已经绑定到了指定的类别上,就认为其他三个参数也绑定上来了,此时就不需要再绑定了; // 如果没有绑定,则要将这四个参数一次性全部绑定到此指定的类别上 if (parameterHasBeenAddedToProject && !faceParaHasInsertedIntoThatCategory) { Autodesk.Revit.DB.Binding parameterBinding = doc.ParameterBindings.get_Item(exdef_FaceIdTag); ((InstanceBinding)parameterBinding).Categories.Insert(myCategory); // 将新的类别添加到 binding 的类别集合中 // 重新进行绑定 bindingMap.ReInsert(exdef_FaceIdTag, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); bindingMap.ReInsert(exdef_FaceType, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); bindingMap.ReInsert(exdef_Volumn, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); bindingMap.ReInsert(exdef_Area, parameterBinding, BuiltInParameterGroup.PG_IDENTITY_DATA); } }
private void btnOK_Click(object sender, EventArgs e) { TaskDialog taskDialog = new TaskDialog("Shared Parameter Creator"); taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconNone; taskDialog.MainInstruction = "Are you sure you want to create the Shared Parameters file?"; taskDialog.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No; fullFile_Excel = txtCSVFile.Text; insertIntoProjectParameters = chkInsert.Checked; if (fullFile_Excel == string.Empty) { TaskDialog.Show("No File Provided", "Make sure you have created a file with the .csv extension."); } else { if (taskDialog.Show() == TaskDialogResult.Yes) { try { Category category = null; CategorySet categorySet = null; InstanceBinding instanceBinding = null; Autodesk.Revit.DB.Binding typeBinding = null; BindingMap bindingMap = null; categorySet = myCommandData.Application.Application.Create.NewCategorySet(); instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet); typeBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet); bindingMap = myCommandData.Application.ActiveUIDocument.Document.ParameterBindings; DefinitionFile sharedParametersFile; string fileName = string.Empty; string filePath = string.Empty; filePath = Path.GetDirectoryName(fullFile_Excel); fileName = Path.GetFileNameWithoutExtension(fullFile_Excel); fullFile_Parameters = filePath + "\\" + fileName + ".txt"; // THE SHARED PARAMETER FILE sharedParametersFile = OpenSharedParametersFile(myCommandData.Application.Application); DefinitionGroup sharedParameterDefinition = null; Definition definition = null; string strTextLine = string.Empty; StreamReader objReader = new System.IO.StreamReader(fullFile_Excel); System.Collections.Specialized.StringCollection parameterCollection = new System.Collections.Specialized.StringCollection(); while (objReader.Peek() != -1) { strTextLine = objReader.ReadLine(); parameterCollection.Add(strTextLine); } //REVIT TRANSACTION Transaction trans = new Transaction(myRevitDoc, "Create Shared Parameters"); trans.Start(); foreach (string param in parameterCollection) { // A, appliesTo, CATEGORY // B, sharedParameterGroup, SHARED PARAMETER GROUP // C, parameterDataType, DATA TYPE // D, bindType, BINDING TYPE // E, PARAMETER NAME string appliesTo = string.Empty; string groupUnder = string.Empty; string sharedParameterGroup = string.Empty; ParameterType parameterDataType; parameterDataType = ParameterType.Text; string parameterDataType_Test = string.Empty; string bindType = string.Empty; string parameterName = string.Empty; char[] chrSeparator = new char[] { ',' }; string[] arrValues = param.Split(chrSeparator, StringSplitOptions.None); appliesTo = arrValues[0]; sharedParameterGroup = arrValues[1]; parameterDataType_Test = arrValues[2]; bindType = arrValues[3]; parameterName = arrValues[4]; switch (parameterDataType_Test) { case "Text": parameterDataType = ParameterType.Text; break; case "Integer": parameterDataType = ParameterType.Integer; break; case "Number": parameterDataType = ParameterType.Number; break; case "Length": parameterDataType = ParameterType.Length; break; case "Area": parameterDataType = ParameterType.Area; break; case "Volume": parameterDataType = ParameterType.Volume; break; case "Angle": parameterDataType = ParameterType.Angle; break; case "Slope": parameterDataType = ParameterType.Slope; break; case "Currency": parameterDataType = ParameterType.Currency; break; case "Mass Density": parameterDataType = ParameterType.MassDensity; break; case "URL": parameterDataType = ParameterType.URL; break; case "Material": parameterDataType = ParameterType.Material; break; case "Image": parameterDataType = ParameterType.Image; break; case "Yes/No": parameterDataType = ParameterType.YesNo; break; default: parameterDataType = ParameterType.Text; break; } sharedParameterDefinition = sharedParametersFile.Groups.get_Item(sharedParameterGroup); if ((sharedParameterDefinition == null)) { sharedParameterDefinition = sharedParametersFile.Groups.Create(sharedParameterGroup); } category = myCommandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(appliesTo); categorySet = myCommandData.Application.Application.Create.NewCategorySet(); categorySet.Insert(category); instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet); typeBinding = myCommandData.Application.Application.Create.NewTypeBinding(categorySet); if ((parameterName != null)) { definition = OpenDefinition(sharedParameterDefinition, parameterName, parameterDataType); } if (insertIntoProjectParameters) { if (bindType == "Type") { bindingMap.Insert(definition, typeBinding, BuiltInParameterGroup.PG_DATA); } else { bindingMap.Insert(definition, instanceBinding, BuiltInParameterGroup.PG_DATA); } } } //END REVIT TRANSACTION trans.Commit(); objReader.Close(); TaskDialog.Show("File Created Sucessfully", "The Shared Parameter file was created successfully"); } catch (Exception ex) { TaskDialog errorMessage = new TaskDialog("Create Shared Parameter Error"); errorMessage.MainInstruction = "An error occurrued while creating the Shared Parameter file." + "\n" + "Please read the following error message below"; errorMessage.MainContent = ex.Message + Environment.NewLine + ex.Source; errorMessage.Show(); } } } }
private void InsertIntoProjectParameters() { DefinitionFile sharedParametersFile = null; sharedParametersFile = OpenSharedParametersFile(myCommandData.Application.Application); Dictionary <string, BuiltInParameterGroup> groupDict = new Dictionary <string, BuiltInParameterGroup>(); groupDict = BrowserGroupDictionary(); Category revitCategory = null; CategorySet categorySet = null; InstanceBinding instanceBinding = null; Autodesk.Revit.DB.Binding typeBinding = null; BindingMap bindingMap = null; bool emptyValueFlag = false; foreach (DataGridViewRow row in dgvSharedParameters.Rows) { string category = row.Cells["clmCategory"].Value.ToString(); string binding = row.Cells["clmBinding"].Value.ToString(); string browserGroup = row.Cells["clmPropertiesGroup"].Value.ToString(); if (category == "" || binding == "" || browserGroup == "") { emptyValueFlag = true; break; } } if (!emptyValueFlag) { Transaction trans = new Transaction(myRevitDoc, "Insert Into Project Parameters"); trans.Start(); foreach (DataGridViewRow row in dgvSharedParameters.Rows) { string name = row.Cells["clmParamName"].Value.ToString(); string group = row.Cells["clmGroup"].Value.ToString(); string category = row.Cells["clmCategory"].Value.ToString(); string binding = row.Cells["clmBinding"].Value.ToString(); string browserGroup = row.Cells["clmPropertiesGroup"].Value.ToString(); revitCategory = myCommandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(category); categorySet = myCommandData.Application.Application.Create.NewCategorySet(); categorySet.Insert(revitCategory); instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet); typeBinding = myCommandData.Application.Application.Create.NewTypeBinding(categorySet); bindingMap = myCommandData.Application.ActiveUIDocument.Document.ParameterBindings; ExternalDefinition extDef = GetSharedParameter(sharedParametersFile, group, name); BuiltInParameterGroup paramGroup; paramGroup = groupDict[browserGroup]; if (binding == "Type") { bindingMap.Insert(extDef, typeBinding, paramGroup); } else { bindingMap.Insert(extDef, instanceBinding, paramGroup); } } trans.Commit(); TaskDialog.Show("Insert into Project Parameters", "The Shared Parameters were inserted successfully"); this.Close(); } else { TaskDialog td = new TaskDialog("Insert into Project Parameters"); td.MainInstruction = "Invalid value(s)"; td.MainContent = "Specify a value for Binding, Category, and Properties Group for each parameter before inserting into Project Parameters"; td.Show(); } }
public static ExternalDefinition CreateSharedParameter(Document doc, Application app, string name, ParameterType type, BuiltInCategory cat, BuiltInParameterGroup group, bool instance) { using (Transaction t = new Transaction(doc)) { t.Start($"Add shared parameter {name}"); try { // save the path to the current shared parameters file string oriFile = app.SharedParametersFilename; // initialize a temporary shared param file string tempFile = Path.GetTempFileName() + ".txt"; // assign the temporary shared param file to the current application using (System.IO.File.Create(tempFile)) { } app.SharedParametersFilename = tempFile; // initialize some external definition creation options, passing in our param name and type var defOptions = new ExternalDefinitionCreationOptions(name, type) { Visible = true, }; // add the shared parameter to the temporary shared parameter file ExternalDefinition def = app .OpenSharedParameterFile() .Groups .Create("UDP Parameters") // create a new shared parameter group called UDP parameters .Definitions .Create(defOptions) as ExternalDefinition; // add the shared param using the options specified above // reset the application's shared parameter file to the original app.SharedParametersFilename = oriFile; // delete the temporary shared param file System.IO.File.Delete(tempFile); // create a new category set and add our category to the category set CategorySet categorySet = app.Create.NewCategorySet(); Category category = doc.Settings.Categories.get_Item(cat); categorySet.Insert(category); // initialize a binding to our category set Autodesk.Revit.DB.Binding binding = app.Create.NewTypeBinding(categorySet); if (instance) { binding = app.Create.NewInstanceBinding(categorySet); // initialize an instance binding if necessary } // bind our new shared parameter to the category set BindingMap map = (doc.ParameterBindings); // check if the binding is successful if (!map.Insert(def, binding, group)) { WF.MessageBox.Show($"Error in RevitMethods.AddSharedParameter: parameter '{name}' was not binded successfully."); t.RollBack(); } // return the external definition t.Commit(); return(def); } catch (Exception e) { WF.MessageBox.Show($"Error in RevitMethods.AddSharedParameter, parameter '{name}': {e}"); t.RollBack(); return(null); } } }
/// <summary> /// /// </summary> /// <param name="doc"></param> /// <param name="cat"></param> /// <param name="paramName"></param> /// <param name="grpName"></param> /// <param name="paramType"></param> /// <param name="visible"></param> /// <param name="instanceBinding"></param> /// <returns></returns> public static BindSharedParamResult BindSharedParam(DocRvt doc, Category cat, string paramName, string grpName, ParameterType paramType, bool visible, bool instanceBinding) { try // generic { AppRvt app = doc.Application; // This is needed already here to store old ones for re-inserting CategorySet catSet = app.Create.NewCategorySet(); // Loop all Binding Definitions // IMPORTANT NOTE: Categories.Size is ALWAYS 1 !? For multiple categories, there is really one pair per each // category, even though the Definitions are the same... DefinitionBindingMapIterator iter = doc.ParameterBindings.ForwardIterator(); while (iter.MoveNext()) { Definition def = iter.Key; ElementBinding elemBind = (ElementBinding)iter.Current; // Got param name match if (paramName.Equals(def.Name, StringComparison.CurrentCultureIgnoreCase)) { // Check for category match - Size is always 1! if (elemBind.Categories.Contains(cat)) { // Check Param Type if (paramType != def.ParameterType) { return(BindSharedParamResult.eWrongParamType); } // Check Binding Type if (instanceBinding) { if (elemBind.GetType() != typeof(InstanceBinding)) { return(BindSharedParamResult.eWrongBindingType); } } else { if (elemBind.GetType() != typeof(TypeBinding)) { return(BindSharedParamResult.eWrongBindingType); } } // Check Visibility - cannot (not exposed) // If here, everything is fine, ie already defined correctly return(BindSharedParamResult.eAlreadyBound); } // If here, no category match, hence must store "other" cats for re-inserting else { foreach (Category catOld in elemBind.Categories) { catSet.Insert(catOld); //1 only, but no index... } } } } // If here, there is no Binding Definition for it, so make sure Param defined and then bind it! DefinitionFile defFile = GetOrCreateSharedParamsFile(app); DefinitionGroup defGrp = GetOrCreateSharedParamsGroup(defFile, grpName); Definition definition = GetOrCreateSharedParamDefinition(defGrp, paramType, paramName, visible); catSet.Insert(cat); BindingRvt bind = null; if (instanceBinding) { bind = app.Create.NewInstanceBinding(catSet); } else { bind = app.Create.NewTypeBinding(catSet); } // There is another strange API "feature". If param has EVER been bound in a project (in above iter pairs or even if not there but once deleted), .Insert always fails!? Must use .ReInsert in that case. // See also similar findings on this topic in: http://thebuildingcoder.typepad.com/blog/2009/09/adding-a-category-to-a-parameter-binding.html - the code-idiom below may be more generic: if (doc.ParameterBindings.Insert(definition, bind)) { return(BindSharedParamResult.eSuccessfullyBound); } else { if (doc.ParameterBindings.ReInsert(definition, bind)) { return(BindSharedParamResult.eSuccessfullyBound); } else { return(BindSharedParamResult.eFailed); } } } catch (Exception ex) { MessageBox.Show(string.Format("Error in Binding Shared Param: {0}", ex.Message)); return(BindSharedParamResult.eFailed); } //return BindSharedParamResult.eSuccessfullyBound; }
public string myMethod_BindParameters(string path, bool IsTypeParameter) { UIDocument uidoc = myWindow1.commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; string myStringSharedParameterFileName = ""; if (uidoc.Application.Application.SharedParametersFilename != null) { myStringSharedParameterFileName = uidoc.Application.Application.SharedParametersFilename; //Q:\Revit Revit Revit\Template 2018\PRL_Parameters.txt } int eL = -1; try { /// TECHNIQUE 16 OF 19 (EE16_AddSharedParameters_InVariousWays.cs) ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ADDING SHARED PARAMETERS IN VARIOUS WAYS ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ /// /// Interfaces and ENUM's: /// /// /// Demonstrates classes:: /// DefinitionFile /// CategorySet /// DefinitionGroup /// Definition /// Binding /// /// /// Key methods: /// uidoc.Application.Application.OpenSharedParameterFile(); /// catSet.Insert( /// myDefinitionFile.Groups.get_Item( /// uidoc.Application.Application.Create.NewTypeBinding( /// uidoc.Application.Application.Create.NewInstanceBinding( /// doc.ParameterBindings.Insert( /// /// famDoc.FamilyManager.AddParameter( /// /// /// /// https://github.com/joshnewzealand/Revit-API-Playpen-CSharp uidoc.Application.Application.SharedParametersFilename = path; DefinitionFile myDefinitionFile = uidoc.Application.Application.OpenSharedParameterFile(); if (myDefinitionFile == null) { DatabaseMethods.writeDebug(path + Environment.NewLine + Environment.NewLine + "File does not exist OR cannot be opened.", true); return(""); } CategorySet catSet = uidoc.Application.Application.Create.NewCategorySet(); foreach (Category myCatttt in doc.Settings.Categories) { if (myCatttt.AllowsBoundParameters) { catSet.Insert(myCatttt); } } string myStringCollectup = ""; DefinitionGroup group = myDefinitionFile.Groups.get_Item("Default"); if (!IsTypeParameter) { using (Transaction tx = new Transaction(doc)) { tx.Start("Shared parameters to Project"); foreach (Definition myDefinition in group.Definitions) { myStringCollectup = myStringCollectup + " • " + myDefinition.Name + Environment.NewLine; Binding binding = IsTypeParameter ? uidoc.Application.Application.Create.NewTypeBinding(catSet) as Binding : uidoc.Application.Application.Create.NewInstanceBinding(catSet) as Binding; doc.ParameterBindings.Insert(myDefinition, binding, BuiltInParameterGroup.PG_IDENTITY_DATA); } tx.Commit(); } myStringCollectup = (IsTypeParameter ? "Type" : "Instance") + " parameters added to Project (all categories):" + Environment.NewLine + myStringCollectup; } if (IsTypeParameter) { if (doc.GetElement(new ElementId(myWindow2.myIntegerUpDown.Value.Value)) != null) //i would rather this come from the spinner so we can select other entities { Element myElement = doc.GetElement(new ElementId(myWindow2.myIntegerUpDown.Value.Value)) as Element; if (myElement.GetType() == typeof(FamilyInstance)) { FamilyInstance myFamilyInstance = myElement as FamilyInstance; Family myFamily = ((FamilySymbol)doc.GetElement(myFamilyInstance.GetTypeId())).Family; if (myFamily.IsEditable) { Document famDoc = null; famDoc = doc.EditFamily(myFamily); bool myBool_GoForthAndAddParameters = false; foreach (Definition myDefinition in group.Definitions) { myStringCollectup = myStringCollectup + " • " + myDefinition.Name + Environment.NewLine; if (famDoc.FamilyManager.Parameters.Cast <FamilyParameter>().Where(x => x.Definition.Name == myDefinition.Name).Count() == 0) { myBool_GoForthAndAddParameters = true; } } if (myBool_GoForthAndAddParameters) { using (Transaction tx = new Transaction(famDoc)) { tx.Start("Shared parameters to Family"); foreach (ExternalDefinition eD in group.Definitions) { if (famDoc.FamilyManager.Parameters.Cast <FamilyParameter>().Where(x => x.Definition.Name == eD.Name).Count() == 0) { famDoc.FamilyManager.AddParameter(eD, BuiltInParameterGroup.PG_IDENTITY_DATA, false); } } tx.Commit(); } myFamily = famDoc.LoadFamily(doc, new FamilyOption()); } famDoc.Close(false); } myStringCollectup = (IsTypeParameter ? "Type" : "Instance") + " parameters added to Family:" + Environment.NewLine + myStringCollectup; } else { using (Transaction tx = new Transaction(doc)) { tx.Start("Shared parameters to Project"); CategorySet catSet2 = uidoc.Application.Application.Create.NewCategorySet(); catSet2.Insert(myElement.Category); foreach (Definition myDefinition in group.Definitions) { myStringCollectup = myStringCollectup + " • " + myDefinition.Name + Environment.NewLine; Binding binding = IsTypeParameter ? uidoc.Application.Application.Create.NewTypeBinding(catSet2) as Binding : uidoc.Application.Application.Create.NewInstanceBinding(catSet2) as Binding; doc.ParameterBindings.Insert(myDefinition, binding, BuiltInParameterGroup.PG_IDENTITY_DATA); } tx.Commit(); } myStringCollectup = (IsTypeParameter ? "Type" : "Instance") + " parameters added to Category: " + myElement.Category.Name + Environment.NewLine + myStringCollectup; } } else { myStringCollectup = "Please use 'Acquire Selected' button."; } } if (myStringSharedParameterFileName != "") { uidoc.Application.Application.SharedParametersFilename = myStringSharedParameterFileName; } return(myStringCollectup); } #region catch and finally catch (Exception ex) { if (myStringSharedParameterFileName != "") { uidoc.Application.Application.SharedParametersFilename = myStringSharedParameterFileName; } _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE17_AddSharedParameters_InVariousWays, error line:" + eL + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); return(""); } finally { } #endregion }
private bool Populate(ProjectParameter parameter) { if (Utils.IsAlreadyBound(doc, parameter.Name)) { Cancel(); Message = "Parameters already exists. Command will not be executed."; return(false); } using (Transaction tx = new Transaction(doc)) { tx.Start("Create per doc Parameters"); // get the current shared params definition file DefinitionFile sharedParamsFile = Utils.GetSharedParamsFile(uiapp.Application); if (null == sharedParamsFile) { Message = "Please, make sure you have set the Shared Parameters file for this project."; return(false); } // get or create the shared params group DefinitionGroup sharedParamsGroup = Utils.GetOrCreateSharedParamsGroup( sharedParamsFile, parameter.GroupName); if (null == sharedParamsGroup) { Message = "Error getting the shared params group."; return(false); } // param Definition docParamDef = Utils.GetOrCreateSharedParamsDefinition( sharedParamsGroup, ParameterType.Text, parameter.Name, parameter.Tooltip, true); if (null == docParamDef) { Message = "Error creating visible per-doc parameter."; return(false); } try { CategorySet catSet = Utils.AssignableCategories(uiapp, doc); Autodesk.Revit.DB.Binding binding = null; if (parameter.Type.Equals("Instance")) { binding = uiapp.Application.Create.NewInstanceBinding(catSet); if (parameter.GroupName.Equals("Budget")) { doc.ParameterBindings.Insert(docParamDef, binding); } else { doc.ParameterBindings.Insert(docParamDef, binding, BuiltInParameterGroup.PG_COUPLER_ARRAY); } } else { binding = uiapp.Application.Create.NewTypeBinding(catSet); if (parameter.GroupName.Equals("Budget")) { doc.ParameterBindings.Insert(docParamDef, binding); } else { doc.ParameterBindings.Insert(docParamDef, binding, BuiltInParameterGroup.PG_COUPLER_ARRAY); } } } catch (Exception e) { Message = "Error binding shared parameter: " + e.Message; return(false); } tx.Commit(); return(true); } }