// 定義參數與綁定類型的Function private bool setNewParameterToTypeWall(UIApplication app, DefinitionFile myDefinitionFile) { // 共用參數文檔中包含了Group,代表參數所屬的群組, // 而Group內又包含了Definition,也就是你想增加的參數, // 欲新增Definition首先必須新增一個Group DefinitionGroups myGroups = myDefinitionFile.Groups; DefinitionGroup myGroup = myGroups.Create("參數群組"); // 創建Definition的定義以及其儲存類型 ExternalDefinitionCreationOptions options = new ExternalDefinitionCreationOptions("聯絡人", ParameterType.Text); Definition myDefinition = myGroup.Definitions.Create(options); // 創建品類集並插入牆品類到裡面 CategorySet myCategories = app.Application.Create.NewCategorySet(); // 使用BuiltInCategory來取得牆品類 Category myCategory = app.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_Walls); myCategories.Insert(myCategory); // 根據品類創建類型綁定的物件 TypeBinding typeBinding = app.Application.Create.NewTypeBinding(myCategories); // 取得當前文件中所有的類型綁定 BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings; // 將客製化的參數定義綁定到文件中 bool typeBindOK = bindingMap.Insert(myDefinition, typeBinding, BuiltInParameterGroup.PG_TEXT); return(typeBindOK); }
PropertyCellType GetType(object item) { if (TypeBinding == null) { return(null); } var typeId = TypeBinding.GetValue(item); return(types.FirstOrDefault(r => r.CanDisplay(typeId))); }
public void AddBindings(Document doc) { Binding binding; if (Instance) { binding = new InstanceBinding(GetCategories(doc)); } else { binding = new TypeBinding(GetCategories(doc)); } // assumes transaction open doc.ParameterBindings.Insert(Definition, binding, ParameterGroup); }
public bool RemoveOrAddFromRebarCategory(Document doc, Element elem, bool addOrDeleteCat) { Application app = doc.Application; ElementBinding elemBind = this.GetBindingByParamName(Name, doc); //получаю список категорий CategorySet newCatSet = app.Create.NewCategorySet(); int rebarcatid = new ElementId(BuiltInCategory.OST_Rebar).IntegerValue; foreach (Category cat in elemBind.Categories) { int catId = cat.Id.IntegerValue; if (catId != rebarcatid) { newCatSet.Insert(cat); } } if (addOrDeleteCat) { Category cat = elem.Category; newCatSet.Insert(cat); } TypeBinding newBind = app.Create.NewTypeBinding(newCatSet); if (doc.ParameterBindings.Insert(def, newBind, paramGroup)) { return(true); } else { if (doc.ParameterBindings.ReInsert(def, newBind, paramGroup)) { return(true); } else { return(false); } } }
public void AddToProjectParameters(Document doc, Element elem) { Application app = doc.Application; //string oldSharedParamsFile = app.SharedParametersFilename; 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 == Name) { exDef = def as ExternalDefinition; } } } if (exDef == null) { throw new Exception("В файле общих параметров не найден общий параметр " + Name); } CategorySet catSet = app.Create.NewCategorySet(); catSet.Insert(elem.Category); TypeBinding newBind = app.Create.NewTypeBinding(catSet); doc.ParameterBindings.Insert(exDef, newBind, paramGroup); //app.SharedParametersFilename = oldSharedParamsFile; Parameter testParam = elem.LookupParameter(Name); if (testParam == null) { throw new Exception("Не удалось добавить обший параметр " + Name); } }
Stream(ArrayList data, ElementBinding elemBind) { data.Add(new Snoop.Data.ClassSeparator(typeof(ElementBinding))); data.Add(new Snoop.Data.Enumerable("Categories", elemBind.Categories)); InstanceBinding instBind = elemBind as InstanceBinding; if (instBind != null) { Stream(data, instBind); return; } TypeBinding typeBind = elemBind as TypeBinding; if (typeBind != null) { Stream(data, typeBind); return; } }
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(); } }
/// <summary> /// This method takes a category and information /// about a project parameter and adds a binding /// to the category for the parameter. It will /// throw an exception if the parameter is already /// bound to the desired category. It returns /// whether or not the API reports that it /// successfully bound the parameter to the /// desired category. /// </summary> /// <param name="doc">The project document in which the project parameter has been defined</param> /// <param name="projectParameterData">Information about the project parameter</param> /// <param name="category">The additional category to which to bind the project parameter</param> /// <returns></returns> static bool AddProjectParameterBinding( Document doc, ProjectParameterData projectParameterData, Category category) { // Following good SOA practices, first validate incoming parameters if (doc == null) { throw new ArgumentNullException("doc"); } if (doc.IsFamilyDocument) { throw new Exception( "doc can not be a family document."); } if (projectParameterData == null) { throw new ArgumentNullException( "projectParameterData"); } if (category == null) { throw new ArgumentNullException("category"); } bool result = false; CategorySet cats = projectParameterData.Binding .Categories; if (cats.Contains(category)) { // It's already bound to the desired category. // Nothing to do. string errorMessage = string.Format( "The project parameter '{0}' is already bound to the '{1}' category.", projectParameterData.Definition.Name, category.Name); throw new Exception(errorMessage); } cats.Insert(category); // See if the parameter is an instance or type parameter. InstanceBinding instanceBinding = projectParameterData.Binding as InstanceBinding; if (instanceBinding != null) { // Is an Instance parameter InstanceBinding newInstanceBinding = doc.Application.Create .NewInstanceBinding(cats); if (doc.ParameterBindings.ReInsert( projectParameterData.Definition, newInstanceBinding)) { result = true; } } else { // Is a type parameter TypeBinding typeBinding = doc.Application.Create .NewTypeBinding(cats); if (doc.ParameterBindings.ReInsert( projectParameterData.Definition, typeBinding)) { result = true; } } return(result); }
//---------------------------------------------------------- public string Them_Hoac_Xoa_Parameter_Trong_Project(UIApplication uiapp, Document doc) { string result = "F"; try { Transaction transaction = new Transaction(doc); transaction.Start("Parameters"); var enums = Enum.GetValues(typeof(BuiltInCategory)); var enums1 = Enum.GetValues(typeof(BuiltInParameterGroup)); var categories = doc.Settings.Categories; foreach (data_group_share_parameter item in my_group_share_parameter) { DefinitionFile parafile = uiapp.Application.OpenSharedParameterFile(); if (parafile != null) { DefinitionGroup myGroup = parafile.Groups.get_Item(item.ten_group_parameter); foreach (data_item_share_parameter subitem in item.Children) { if (subitem.exist_parameter == true) { //BuiltInParameterGroup builtInParameterGroup = BuiltInParameterGroup.PG_TEXT; //foreach (BuiltInParameterGroup builtIn in enums1) //{ // if (builtIn.ToString().Split('_')[0] == subitem.ten_parameter && builtIn != BuiltInParameterGroup.INVALID) builtInParameterGroup = builtIn; //} Definition myDefinition_ProductDate = myGroup.Definitions.get_Item(subitem.ten_parameter); CategorySet myCategories = uiapp.Application.Create.NewCategorySet(); foreach (BuiltInCategory buildCategory in enums) { try { Category cate = categories.get_Item(buildCategory); if (cate.AllowsBoundParameters == true && cate.CategoryType.ToString() == "Model") { myCategories.Insert(cate); } } catch (Exception) { } } try { BindingMap bindingMap = doc.ParameterBindings; if (subitem.ten_parameter != "Chiều dày hoàn thiện") { InstanceBinding instanceBinding = uiapp.Application.Create.NewInstanceBinding(myCategories); bindingMap.Insert(myDefinition_ProductDate, instanceBinding); } else { TypeBinding instanceBinding = uiapp.Application.Create.NewTypeBinding(myCategories); bindingMap.Insert(myDefinition_ProductDate, instanceBinding); } if (my_data_parameter_current.Any(x => x.ten_parameter == subitem.ten_parameter) == false) { my_data_parameter_current.Add(new data_parameter() { ten_parameter = subitem.ten_parameter }); } } catch (Exception) { } } else { try { Definition myDefinition_ProductDate = myGroup.Definitions.get_Item(subitem.ten_parameter); BindingMap bindingMap = doc.ParameterBindings; bindingMap.Remove(myDefinition_ProductDate); data_parameter item_remove = my_data_parameter_current.First(x => x.ten_parameter == subitem.ten_parameter); if (item_remove != null) { my_data_parameter_current.Remove(item_remove); } } catch (Exception) { } } try { if (my_data_parameter_current.Any(x => x.ten_parameter == subitem.ten_parameter) == false) { my_data_parameter_need.First(x => x.ten_parameter == subitem.ten_parameter).color = Source.color_error; } else { my_data_parameter_need.First(x => x.ten_parameter == subitem.ten_parameter).color = Source.color; } thong_tin_parameter.Items.Refresh(); } catch (Exception) { } } } else { MessageBox.Show("Not found share parameter file!!!", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error); } } result = "S"; transaction.Commit(); } catch (Exception ex) { MessageBox.Show(ex.Message); } return(result); }
static void BindType(TypeBinding type, Bindings bindings) { try { var t = type.Definition; var h = GetHierarchy(type.Definition).ToList(); var bh = h.Select(x => bindings.Types.FirstOrDefault(y => y.Name == x.Item2.FullName)) .Where(x => x != null) .ToList(); string Name(TypeReference tref) { if (tref.IsGenericParameter) { var r = ResolveGenericParameter(tref, h); return(Name(r)); } if (tref.IsGenericInstance) { var n = tref.Name.Substring(0, tref.Name.IndexOf('`')); var ns = tref.Namespace; if (tref.IsNested) { n = tref.DeclaringType.Name + "." + n; ns = tref.DeclaringType.Namespace; } var args = string.Join(", ", ((GenericInstanceType)tref).GenericArguments.Select(Name)); return($"{ns}.{n}<{args}>"); } switch (tref.FullName) { case "System.String": return("string"); case "System.Boolean": return("bool"); case "System.Int32": return("int"); case "System.Double": return("double"); case "System.Single": return("float"); default: if (bindings.Types.FirstOrDefault(x => x.Name == tref.FullName) is TypeBinding tb) { return(tb.BoundName); } return(tref.FullName.Replace('/', '.')); } } var ctor = t.Methods .Where(x => x.IsConstructor && x.IsPublic) .OrderBy(x => x.Parameters.Count) .FirstOrDefault(); var w = new StringWriter(); w.Write($"public partial class {type.BoundName}"); var baseType = bh.Count > 1 ? bh[1] : null; if (baseType != null) { w.WriteLine($" : {baseType.BoundName}"); } else { w.WriteLine(); } w.WriteLine("{"); // // Properties // var allmembers = (from x in bh from y in x.Members select y).ToList(); foreach (var m in type.Members) { w.WriteLine($"\tpublic {Name(m.BoundType)} {m.Name} {{ get; }}"); } // // Constructor // w.Write($"\tpublic {type.BoundName}("); var head = ""; foreach (var m in allmembers) { w.Write($"{head}{Name(m.BoundType)} {m.LowerName} = {m.BoundConstDefault}"); head = ", "; } w.Write($")"); if (baseType != null) { w.WriteLine(); w.Write("\t\t: base("); head = ""; foreach (var b in bh.Skip(1)) { foreach (var m in b.Members) { w.Write($"{head}{m.LowerName}"); head = ", "; } } w.Write($")"); } w.WriteLine(" {"); foreach (var m in type.Members) { var v = m.LowerName; if (m.BoundConstDefault != m.Default) { v = $"{m.LowerName} == {m.ConstDefault} ? {m.Default} : {m.LowerName}"; } w.WriteLine($"\t\t{m.Name} = {v};"); } w.WriteLine("\t}"); // // With* // foreach (var m in allmembers) { var owner = bh.FirstOrDefault(x => x.Members.Contains(m)); if (owner == type) { w.Write($"\tpublic virtual {type.BoundName} With{m.Name}({Name(m.BoundType)} {m.LowerName}) => new {type.BoundName}("); } else { w.Write($"\tpublic override {owner.BoundName} With{m.Name}({Name(m.BoundType)} {m.LowerName}) => new {type.BoundName}("); } head = ""; foreach (var o in allmembers) { var v = o == m ? m.LowerName : o.Name; w.Write($"{head}{v}"); head = ", "; } w.WriteLine(");"); } // // Equality // w.WriteLine("\tpublic override bool Equals(object obj) {"); w.WriteLine($"\t\tif (obj == null || GetType() != obj.GetType()) return false;"); w.WriteLine($"\t\tvar o = ({type.BoundName})obj;"); w.Write("\t\treturn "); if (allmembers.Count > 0) { head = ""; foreach (var m in allmembers) { if (!string.IsNullOrEmpty(m.Equality)) { w.Write($"{head}{m.Equality}"); } else { w.Write($"{head}{m.Name} == o.{m.Name}"); } head = " && "; } w.WriteLine(";"); } else { w.WriteLine("true;"); } w.WriteLine("\t}"); // // Hash Code // w.WriteLine("\tpublic override int GetHashCode() {"); if (baseType != null) { w.WriteLine($"\t\tvar hash = base.GetHashCode();"); } else { w.WriteLine($"\t\tvar hash = 17;"); } foreach (var m in type.Members) { var bt = ResolveGenericParameter(m.BoundType, h); if (bt.IsValueType) { w.WriteLine($"\t\thash = hash * 37 + {m.Name}.GetHashCode();"); } else { w.WriteLine($"\t\thash = hash * 37 + ({m.Name} != null ? {m.Name}.GetHashCode() : 0);"); } } w.WriteLine("\t\treturn hash;"); w.WriteLine("\t}"); // // Creates // if (t.IsAbstract || ctor == null || ctor.Parameters.Count != 0) { w.WriteLine($"\tpublic virtual {t.FullName} Create{t.Name}() => throw new System.NotSupportedException(\"Cannot create {t.FullName} from \" + GetType().FullName);"); } else { w.WriteLine($"\tpublic virtual {t.FullName} Create{t.Name}() {{"); w.WriteLine($"\t\tvar target = new {t.FullName}();"); w.WriteLine($"\t\tApply(target);"); w.WriteLine($"\t\treturn target;"); w.WriteLine("\t}"); foreach (var b in bh.Skip(1)) { w.WriteLine($"\tpublic override {b.Definition.FullName} Create{b.Definition.Name}() => Create{t.Name}();"); } } // // Apply // var refToken = t.IsValueType ? "ref " : ""; w.WriteLine($"\tpublic virtual void Apply({refToken}{t.FullName} target) {{"); if (baseType != null) { w.WriteLine($"\t\tbase.Apply(target);"); } foreach (var m in type.Members) { var bt = ResolveGenericParameter(m.BoundType, h); if (!string.IsNullOrEmpty(m.Apply)) { w.WriteLine($"\t\t{m.Apply}"); } else if (GetListItemType(m.BoundType, h) is var etype && etype != null) { w.WriteLine($"\t\tif ({m.Name} == null || {m.Name}.Count == 0) target.{m.Name}?.Clear();"); w.WriteLine($"\t\telse {{"); w.WriteLine($"\t\t\twhile (target.{m.Name}.Count > {m.Name}.Count) target.{m.Name}.RemoveAt(target.{m.Name}.Count - 1);"); w.WriteLine($"\t\t\tvar n = target.{m.Name}.Count;"); w.WriteLine($"\t\t\tfor (var i = n; i < {m.Name}.Count; i++) target.{m.Name}.Insert(i, {m.Name}[i].Create{etype.Name}());"); w.WriteLine($"\t\t\tfor (var i = 0; i < n; i++) {m.Name}[i].Apply(target.{m.Name}[i]);"); w.WriteLine($"\t\t}}"); } else { if (bindings.FindType(bt.FullName) is TypeBinding b) { if (bt.IsValueType) { w.WriteLine($"\t\ttarget.{m.Name} = {m.Name}.Create{bt.Name}();"); } else { w.WriteLine($"\t\tif ({m.Name} != null) {{"); w.WriteLine($"\t\t\tif (target.{m.Name} is {bt.FullName} {m.LowerName}) {m.Name}.Apply({m.LowerName});"); w.WriteLine($"\t\t\telse target.{m.Name} = {m.Name}.Create{bt.Name}();"); w.WriteLine($"\t\t}} else target.{m.Name} = null;"); } } else { w.WriteLine($"\t\ttarget.{m.Name} = {m.Name};"); } } }
private static Parameter AddParameterBase(Document doc, Element element, string parameterName, int parameterSetId, ParameterType parameterType) { Category category = element.Category; if (category == null) { Importer.TheLog.LogWarning(parameterSetId, "Can't add parameters for element with no category.", true); return(null); } else if (IsDisallowedCategory(category)) { Importer.TheLog.LogWarning(parameterSetId, "Can't add parameters for category: " + category.Name, true); return(null); } Guid guid; bool isElementType = (element is ElementType); DefinitionGroup definitionGroup = isElementType ? Importer.TheCache.DefinitionTypeGroup : Importer.TheCache.DefinitionInstanceGroup; KeyValuePair <string, bool> parameterKey = new KeyValuePair <string, bool>(parameterName, isElementType); bool newlyCreated = false; Definition definition = definitionGroup.Definitions.get_Item(parameterName); if (definition == null) { ExternalDefinitonCreationOptions option = new ExternalDefinitonCreationOptions(parameterName, parameterType); definition = definitionGroup.Definitions.Create(option); newlyCreated = true; } guid = (definition as ExternalDefinition).GUID; Parameter parameter = null; if (definition != null) { ElementBinding binding = null; bool reinsert = false; bool changed = false; if (!newlyCreated) { binding = doc.ParameterBindings.get_Item(definition) as ElementBinding; reinsert = (binding != null); } if (binding == null) { if (isElementType) { binding = new TypeBinding(); } else { binding = new InstanceBinding(); } } if (category != null) { if (category.Parent != null) { category = category.Parent; } if (!reinsert || !binding.Categories.Contains(category)) { changed = true; binding.Categories.Insert(category); } // The binding can fail if we haven't identified a "bad" category above. Use try/catch as a safety net. try { if (changed) { if (reinsert) { doc.ParameterBindings.ReInsert(definition, binding, BuiltInParameterGroup.PG_IFC); } else { doc.ParameterBindings.Insert(definition, binding, BuiltInParameterGroup.PG_IFC); } } parameter = element.get_Parameter(guid); } catch { } } } if (parameter == null) { Importer.TheLog.LogError(parameterSetId, "Couldn't create parameter: " + parameterName, false); } return(parameter); }
private void Stream(ArrayList data, TypeBinding typeBind) { data.Add(new Snoop.Data.ClassSeparator(typeof(TypeBinding))); // Nothing at this level yet! }
private static Parameter AddParameterBase(Document doc, Element element, string parameterName, int parameterSetId, ParameterType parameterType) { Category category = element.Category; if (category == null) { Importer.TheLog.LogWarning(parameterSetId, "Can't add parameters for element with no category.", true); return null; } else if (IsDisallowedCategory(category)) { Importer.TheLog.LogWarning(parameterSetId, "Can't add parameters for category: " + category.Name, true); return null; } Guid guid; bool isElementType = (element is ElementType); DefinitionGroup definitionGroup = isElementType ? Importer.TheCache.DefinitionTypeGroup : Importer.TheCache.DefinitionInstanceGroup; KeyValuePair<string, bool> parameterKey = new KeyValuePair<string, bool>(parameterName, isElementType); bool newlyCreated = false; Definition definition = definitionGroup.Definitions.get_Item(parameterName); if (definition == null) { ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(parameterName, parameterType); definition = definitionGroup.Definitions.Create(option); newlyCreated = true; } guid = (definition as ExternalDefinition).GUID; Parameter parameter = null; if (definition != null) { ElementBinding binding = null; bool reinsert = false; bool changed = false; if (!newlyCreated) { binding = doc.ParameterBindings.get_Item(definition) as ElementBinding; reinsert = (binding != null); } if (binding == null) { if (isElementType) binding = new TypeBinding(); else binding = new InstanceBinding(); } if (category != null) { if (category.Parent != null) category = category.Parent; if (!reinsert || !binding.Categories.Contains(category)) { changed = true; binding.Categories.Insert(category); } // The binding can fail if we haven't identified a "bad" category above. Use try/catch as a safety net. try { if (changed) { if (reinsert) doc.ParameterBindings.ReInsert(definition, binding, BuiltInParameterGroup.PG_IFC); else doc.ParameterBindings.Insert(definition, binding, BuiltInParameterGroup.PG_IFC); } parameter = element.get_Parameter(guid); } catch { } } } if (parameter == null) Importer.TheLog.LogError(parameterSetId, "Couldn't create parameter: " + parameterName, false); return parameter; }
/// <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); }
/// <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; } } }
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(); } }
/// <summary> /// Add shared parameters needed in this sample. /// parameter 1: one string parameter named as "BasalOpening" which is used for customization of door opening for each country. /// parameter 2: one string parameter named as "InstanceOpening" to indicate the door's opening value. /// parameter 3: one YESNO parameter named as "Internal Door" to flag the door is internal door or not. /// </summary> /// <param name="app">Revit application.</param> public static void AddSharedParameters(UIApplication app) { // Create a new Binding object with the categories to which the parameter will be bound. CategorySet categories = app.Application.Create.NewCategorySet(); // get door category and insert into the CategorySet. Category doorCategory = app.ActiveUIDocument.Document.Settings.Categories. get_Item(BuiltInCategory.OST_Doors); categories.Insert(doorCategory); // create one instance binding for "Internal Door" and "InstanceOpening" parameters; // and one type binding for "BasalOpening" parameters InstanceBinding instanceBinding = app.Application.Create.NewInstanceBinding(categories); TypeBinding typeBinding = app.Application.Create.NewTypeBinding(categories); BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings; // Open the shared parameters file // via the private method AccessOrCreateSharedParameterFile DefinitionFile defFile = AccessOrCreateSharedParameterFile(app.Application); if (null == defFile) { return; } // Access an existing or create a new group in the shared parameters file DefinitionGroups defGroups = defFile.Groups; DefinitionGroup defGroup = defGroups.get_Item("DoorProjectSharedParameters"); if (null == defGroup) { defGroup = defGroups.Create("DoorProjectSharedParameters"); } // Access an existing or create a new external parameter definition belongs to a specific group. // for "BasalOpening" if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "BasalOpening", BuiltInCategory.OST_Doors)) { Definition basalOpening = defGroup.Definitions.get_Item("BasalOpening"); if (null == basalOpening) { basalOpening = defGroup.Definitions.Create("BasalOpening", ParameterType.Text, false); } // Add the binding and definition to the document. bindingMap.Insert(basalOpening, typeBinding, BuiltInParameterGroup.PG_GEOMETRY); } // for "InstanceOpening" if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "InstanceOpening", BuiltInCategory.OST_Doors)) { Definition instanceOpening = defGroup.Definitions.get_Item("InstanceOpening"); if (null == instanceOpening) { instanceOpening = defGroup.Definitions.Create("InstanceOpening", ParameterType.Text, true); } // Add the binding and definition to the document. bindingMap.Insert(instanceOpening, instanceBinding, BuiltInParameterGroup.PG_GEOMETRY); } // for "Internal Door" if (!AlreadyAddedSharedParameter(app.ActiveUIDocument.Document, "Internal Door", BuiltInCategory.OST_Doors)) { Definition internalDoorFlag = defGroup.Definitions.get_Item("Internal Door"); if (null == internalDoorFlag) { internalDoorFlag = defGroup.Definitions.Create("Internal Door", ParameterType.YesNo, true); } // Add the binding and definition to the document. bindingMap.Insert(internalDoorFlag, instanceBinding); } }
public static Parameter AddParameterBase(Document doc, Element element, Category category, string parameterName, int parameterSetId, ForgeTypeId specId) { bool isElementType = (element is ElementType); Definitions definitions = isElementType ? Importer.TheCache.TypeGroupDefinitions : Importer.TheCache.InstanceGroupDefinitions; bool newlyCreated = false; Definition definition = definitions.get_Item(parameterName); if (definition == null) { ExternalDefinitionCreationOptions option = new ExternalDefinitionCreationOptions(parameterName, specId); definition = definitions.Create(option); if (definition == null) { Importer.TheLog.LogError(parameterSetId, "Couldn't create parameter: " + parameterName, false); return(null); } newlyCreated = true; } Guid guid = (definition as ExternalDefinition).GUID; Parameter parameter = null; ElementBinding binding = null; bool reinsert = false; if (!newlyCreated) { BindingMap bindingMap = Importer.TheCache.GetParameterBinding(doc); binding = bindingMap.get_Item(definition) as ElementBinding; reinsert = (binding != null); } if (binding == null) { if (isElementType) { binding = new TypeBinding(); } else { binding = new InstanceBinding(); } } // The binding can fail if we haven't identified a "bad" category above. Use try/catch as a safety net. try { if (!reinsert || !binding.Categories.Contains(category)) { binding.Categories.Insert(category); BindingMap bindingMap = Importer.TheCache.GetParameterBinding(doc); if (reinsert) { bindingMap.ReInsert(definition, binding, BuiltInParameterGroup.PG_IFC); } else { bindingMap.Insert(definition, binding, BuiltInParameterGroup.PG_IFC); } } parameter = element.get_Parameter(guid); } catch { } if (parameter == null) { Importer.TheLog.LogError(parameterSetId, "Couldn't create parameter: " + parameterName, false); } return(parameter); }
Stream(ArrayList data, TypeBinding typeBind) { data.Add(new Snoop.Data.ClassSeparator(typeof(TypeBinding))); // Nothing at this level yet! }
public static bool SetSharedPropertiesBinding(this Document document, ParameterType paramType, CategorySet categoriesForParam, string parameterName, BuiltInParameterGroup group, bool type) #endif { 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); } } var application = document.Application; if (_definitionFile == null) { //ask for the location of the shared parameters file var dialog = new OpenFileDialog(); dialog.CheckFileExists = false; dialog.Title = "Set shared parameter file..."; dialog.ShowDialog(); string shrFilePath = dialog.FileName; if (!String.IsNullOrEmpty(shrFilePath)) { document.SetDefinitionFile(shrFilePath); } } if (_definitionFile == null) { throw new Exception("Definition file must be set before creation of the new parameters."); } var myDefinitionFile = _definitionFile; // Get parameter or create new one var myGroups = myDefinitionFile.Groups; Definition myDefinition = null; var found = false; foreach (var gr in myGroups) { foreach (var def in gr.Definitions) { if (def.Name != parameterName || def.ParameterType != paramType || def.ParameterGroup != @group) { continue; } 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) { var myGroup = myGroups.get_Item(DefaultGroupName) ?? myGroups.Create(DefaultGroupName); // Create a type definition myDefinition = myGroup.Definitions.get_Item(parameterName); if (myDefinition == null) { #if Revit2015 || Revit2016 var options = new ExternalDefinitonCreationOptions(parameterName, paramType) { UserModifiable = editable, Visible = visible, GUID = id }; myDefinition = myGroup.Definitions.Create(options); #elif Revit2014 myDefinition = myGroup.Definitions.Create(parameterName, paramType, visible, ref id); #else myDefinition = myGroup.Definitions.Create(parameterName, paramType); #endif } } //Create an object of TypeBinding or InstanceBinding according to the Categories and "typeBinding" variable // Get the BingdingMap of current document. var bindingMap = document.ParameterBindings; var binding = bindingMap.get_Item(myDefinition); bool bindOk; if (type) { 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) { var 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); } binding = application.Create.NewInstanceBinding(categoriesForParam); } // Bind the definitions to the document bindOk = bindingMap.Insert(myDefinition, binding, group); return(bindOk); }