/// <summary> /// 删除某个类别中的共享参数 /// </summary> /// <param name="doc"></param> /// <param name="groupName">参数组</param> /// <param name="parameterName">参数名</param> /// <param name="moveCategory">类别</param> /// <param name="isInstance">false:类别, true: 实例</param> /// <returns></returns> public bool DeleteShareParameter(Document doc, string groupName, string parameterName, Category moveCategory, bool isInstance) { bool isSuccess = false; if (string.IsNullOrWhiteSpace(path)) { throw new Exception("无效路径"); } doc.Application.SharedParametersFilename = this.path; DefinitionFile file = doc.Application.OpenSharedParameterFile(); if (file == null) { throw new Exception("共享参数文件不存在"); } DefinitionGroups groups = file.Groups; DefinitionGroup group = file.Groups.get_Item(groupName); if (group == null) { throw new Exception("参数组不存在"); } Definition definition = group.Definitions.get_Item(parameterName); if (definition == null) { throw new Exception("共享参数不存在"); } ElementBinding elementBinding = doc.ParameterBindings.get_Item(definition) as ElementBinding; CategorySet set = elementBinding.Categories; CategorySet newSet = new CategorySet(); foreach (Category category in set) { if (category.Name != moveCategory.Name) { newSet.Insert(category); } } if (isInstance) { elementBinding = doc.Application.Create.NewInstanceBinding(newSet); } else { elementBinding = doc.Application.Create.NewTypeBinding(newSet); } doc.ParameterBindings.Remove(definition); if (elementBinding.Categories.Size > 0) { return(doc.ParameterBindings.Insert(definition, elementBinding, BuiltInParameterGroup.PG_TEXT)); } else { return(false); } }
/// <summary> /// Checks if a parameter exists based of a name /// </summary> /// <param name="doc"></param> /// <param name="paramName"></param> /// <returns></returns> private bool ShareParameterExists(Document doc, String paramName) { BindingMap bindingMap = doc.ParameterBindings; DefinitionBindingMapIterator iter = bindingMap.ForwardIterator(); iter.Reset(); while (iter.MoveNext()) { Definition tempDefinition = iter.Key; // find the definition of which the name is the appointed one if (String.Compare(tempDefinition.Name, paramName) != 0) { continue; } // get the category which is bound ElementBinding binding = bindingMap.get_Item(tempDefinition) as ElementBinding; CategorySet bindCategories = binding.Categories; foreach (Category category in bindCategories) { if (category.Name == doc.Settings.Categories.get_Item(BuiltInCategory.OST_Rebar).Name) { return(true); } } } return(false); }
/// <summary> /// Test if the Room binds a specified shared parameter /// </summary> /// <param name="paramName">Parameter name to be checked</param> /// <returns>true, the definition exists, false, doesn't exist.</returns> private bool ShareParameterExists(String paramName) { BindingMap bindingMap = m_document.ParameterBindings; DefinitionBindingMapIterator iter = bindingMap.ForwardIterator(); iter.Reset(); while (iter.MoveNext()) { Definition tempDefinition = iter.Key; // find the definition of which the name is the appointed one if (String.Compare(tempDefinition.Name, paramName) != 0) { continue; } // get the category which is bound ElementBinding binding = bindingMap.get_Item(tempDefinition) as ElementBinding; CategorySet bindCategories = binding.Categories; foreach (Category category in bindCategories) { if (category.Name == m_document.Settings.Categories.get_Item(BuiltInCategory.OST_Rooms).Name) { // the definition with appointed name was bound to Rooms, return true return(true); } } } // // return false if shared parameter doesn't exist return(false); }
/// <summary> /// Get Database Column Definition for ElementBinding /// </summary> /// <param name="bind">ElementBinding for Column Definition</param> /// <param name="table">DataTableHanlder for Special cases</param> /// <returns>Column Definitnion string.</returns> protected virtual string GetColumnDefinition(ElementBinding bind, DataTableHandler table) { string type = GetDatabaseType(bind, table); string defaultDef = null; // Check for Default Value depending on Constraints and Type if (bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement) { defaultDef = "NOT NULL AUTO_INCREMENT"; } else if (bind.DataElement != null && bind.DataElement.AllowDbNull) { defaultDef = "DEFAULT NULL"; } else if (bind.ValueType == typeof(DateTime)) { defaultDef = "NOT NULL DEFAULT '2000-01-01 00:00:00'"; } else { defaultDef = "NOT NULL"; } return(string.Format("`{0}` {1} {2}", bind.ColumnName, type, defaultDef)); }
/// <summary> /// Has the specific document shared parameter already been added ago? /// </summary> /// <param name="doc">Revit project in which the shared parameter will be added.</param> /// <param name="paraName">the name of the shared parameter.</param> /// <param name="boundCategory">Which category the parameter will bind to</param> /// <returns>Returns true if already added ago else returns false.</returns> private static bool AlreadyAddedSharedParameter(Document doc, string paraName, BuiltInCategory boundCategory) { try { BindingMap bindingMap = doc.ParameterBindings; DefinitionBindingMapIterator bindingMapIter = bindingMap.ForwardIterator(); while (bindingMapIter.MoveNext()) { if (bindingMapIter.Key.Name.Equals(paraName)) { ElementBinding binding = bindingMapIter.Current as ElementBinding; CategorySet categories = binding.Categories; foreach (Category category in categories) { if (category.BuiltInCategory == boundCategory) { return(true); } } } } } catch (Exception) { return(false); } return(false); }
/// <summary> /// Get Database Column Definition for ElementBinding /// </summary> /// <param name="bind">ElementBinding for Column Definition</param> /// <param name="table">DataTableHanlder for Special cases</param> /// <returns>Column Definitnion string.</returns> protected virtual string GetColumnDefinition(ElementBinding bind, DataTableHandler table) { string type = GetDatabaseType(bind, table); string defaultDef = null; // Check for Default Value depending on Constraints and Type if (bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement) { defaultDef = "NOT NULL PRIMARY KEY AUTOINCREMENT"; } else if (bind.DataElement != null && bind.DataElement.AllowDbNull) { defaultDef = "DEFAULT NULL"; } else if (bind.ValueType == typeof(DateTime)) { defaultDef = "NOT NULL DEFAULT '2000-01-01 00:00:00'"; } else if (bind.ValueType == typeof(string)) { defaultDef = "NOT NULL DEFAULT ''"; } else { defaultDef = "NOT NULL DEFAULT 0"; } // Force Case Insensitive Text Field to Match MySQL Behavior if (bind.ValueType == typeof(string)) { defaultDef = string.Format("{0} {1}", defaultDef, "COLLATE NOCASE"); } return(string.Format("`{0}` {1} {2}", bind.ColumnName, type, defaultDef)); }
public VertexElement(ElementBinding elementBinding, ElementType elementType, int typeCount, int stride, int ordinal) { this.elementBinding = elementBinding; this.elementType = elementType; this.typeCount = typeCount; this.stride = stride; this.ordinal = ordinal; }
public VertexElement(ElementBinding elementBinding, ElementType elementType, int typeCount, int stride, int ordinal) { this.elementBinding = elementBinding; this.elementType = elementType; this.typeCount = typeCount; this.stride = stride; this.ordinal = ordinal; }
public ParameterInfo(Definition definition, ElementBinding binding) { this.m_parameterIsProject = (definition is ExternalDefinition); this.m_parameterForType = (binding is TypeBinding); this.m_parameterName = definition.Name; this.m_parameterGroup = definition.ParameterGroup; this.m_parameterType = definition.ParameterType; this.m_categories = binding.Categories; }
private void ElementBindidng_Click(object sender, RoutedEventArgs e) { if (IsWindowOpen <ElementBinding>()) { MessageBox.Show("This window is already open!", "Error", MessageBoxButton.OK); } else { EB_window = new ElementBinding(); EB_window.Show(); } }
private Dictionary <string, Dictionary <string, ParameterProperties> > GetProjectParameters() { Dictionary <string, Dictionary <string, ParameterProperties> > paramDictionary = new Dictionary <string, Dictionary <string, ParameterProperties> >(); try { BindingMap bindingMap = m_doc.ParameterBindings; DefinitionBindingMapIterator iterator = bindingMap.ForwardIterator(); while (iterator.MoveNext()) { Definition definition = iterator.Key as Definition; string paramName = definition.Name; ElementBinding binding = iterator.Current as ElementBinding; ParameterProperties pp = new ParameterProperties(); pp.ParameterName = paramName; if (binding is InstanceBinding) { pp.IsInstance = true; } else if (binding is TypeBinding) { pp.IsInstance = false; } foreach (Category category in binding.Categories) { if (!string.IsNullOrEmpty(category.Name)) { if (!paramDictionary.ContainsKey(category.Name)) { Dictionary <string, ParameterProperties> dictionary = new Dictionary <string, ParameterProperties>(); dictionary.Add(pp.ParameterName, pp); paramDictionary.Add(category.Name, dictionary); } else { if (!paramDictionary[category.Name].ContainsKey(pp.ParameterName)) { paramDictionary[category.Name].Add(pp.ParameterName, pp); } } } } } } catch (Exception ex) { MessageBox.Show("Failed to get project parameters\n" + ex.Message, "Get Project Parameters", MessageBoxButton.OK, MessageBoxImage.Warning); } return(paramDictionary); }
//Shared Parameters //----------------- public static bool CheckCreateProjectParameter(Document doc, string param, BuiltInCategory bicCheck) { try { BindingMap map = doc.ParameterBindings; DefinitionBindingMapIterator it = map.ForwardIterator(); it.Reset(); Category cat = Category.GetCategory(doc, bicCheck); CategorySet catSet = new CategorySet(); catSet.Insert(Category.GetCategory(doc, bicCheck)); ElementBinding eb = null; while (it.MoveNext()) { if (param == it.Key.Name) { eb = it.Current as ElementBinding; if (eb.Categories.Contains(cat)) { return(true); } } } Transaction trans = new Transaction(doc); try { trans.Start("Project Parameters"); CreateSharedProjectParameters(doc, param, catSet); trans.Commit(); return(true); } catch (Exception ex) { trans.RollBack(); throw new Exception("Exception in Create Shared Parameters" + ex.Message); } } catch (Exception ex) { throw new Exception("Exception in Check Project Parameter.\n" + ex); } }
public bool AddShadeParameter(Document doc, string groupName, string parameterName, Category category, bool isInstance) { 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) { throw new Exception("没有找到对应的参数,参数名:" + parameterName); } 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, BuiltInParameterGroup.PG_TEXT)); }
AddObjectsToTree(Autodesk.Revit.DB.BindingMap map, TreeNodeCollection curNodes) { if (map.IsEmpty) { return; // nothing to add } // iterate over the map and add items to the tree Autodesk.Revit.DB.DefinitionBindingMapIterator iter = map.ForwardIterator(); while (iter.MoveNext()) { Definition def = iter.Key; ElementBinding elemBind = (ElementBinding)iter.Current; // TBD: not sure if this map is implemented correctly... doesn't seem to be // find out if this one already exists TreeNode defNode = null; foreach (TreeNode tmpNode in curNodes) { if (tmpNode.Text == def.Name) { defNode = tmpNode; break; } } // this one doesn't exist in the tree yet, add it. if (defNode == null) { defNode = new TreeNode(def.Name); defNode.Tag = iter.Current; curNodes.Add(defNode); } if (elemBind != null) { CategorySet cats = elemBind.Categories; foreach (Category cat in cats) { TreeNode tmpNode = new TreeNode(cat.Name); tmpNode.Tag = cat; defNode.Nodes.Add(tmpNode); } } } }
private ElementBinding GetBindingByParamName(String paramName, Document doc) { Application app = doc.Application; DefinitionBindingMapIterator iter = doc.ParameterBindings.ForwardIterator(); while (iter.MoveNext()) { Definition curDef = iter.Key; if (!Name.Equals(curDef.Name)) { continue; } def = curDef; ElementBinding elemBind = (ElementBinding)iter.Current; return(elemBind); } throw new Exception("не найден параметр " + paramName); }
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 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); }
/// <summary> /// Set Value to DataObject Field according to ElementBinding /// Override for SQLite to Handle some Specific Case (Unsigned Int64...) /// </summary> /// <param name="obj">DataObject to Fill</param> /// <param name="bind">ElementBinding for the targeted Member</param> /// <param name="value">Object Value to Fill</param> protected override void DatabaseSetValue(DataObject obj, ElementBinding bind, object value) { try { if (value != null && bind.ValueType == typeof(ulong)) { bind.SetValue(obj, unchecked ((ulong)Convert.ToInt64(value))); return; } } catch (Exception e) { if (Log.IsErrorEnabled) { Log.ErrorFormat("{0}: {1} = {2} doesnt fit to {3}\n{4}", obj.TableName, bind.ColumnName, value.GetType().FullName, bind.ValueType, e); } } base.DatabaseSetValue(obj, bind, value); }
public static bool IsAlreadyBound(Autodesk.Revit.DB.Document doc, string paramName) { 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)) { return(true); } } return(false); }
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 MyProjectSharedParameter(Parameter param, Document doc) { def = param.Definition; Name = def.Name; InternalDefinition intDef = def as InternalDefinition; if (intDef != null) { paramGroup = intDef.ParameterGroup; } guid = param.GUID; ElementBinding elemBind = this.GetBindingByParamName(Name, doc); foreach (Category cat in elemBind.Categories) { categories.Add(cat); } }
public static List <RawProjectParameterInfo> RawGetProjectParametersInfo(Document doc) { RawProjectParameterInfo.FileName = doc.Title; List <RawProjectParameterInfo> paramList = new List <RawProjectParameterInfo>(); BindingMap map = doc.ParameterBindings; DefinitionBindingMapIterator it = map.ForwardIterator(); it.Reset(); while (it.MoveNext()) { ElementBinding eleBinding = it.Current as ElementBinding; InstanceBinding insBinding = eleBinding as InstanceBinding; Definition def = it.Key; if (def != null) { ExternalDefinition extDef = def as ExternalDefinition; bool shared = extDef != null; RawProjectParameterInfo param = new RawProjectParameterInfo { Name = def.Name, Group = def.ParameterGroup, Type = def.ParameterType, ReadOnly = true, // def.IsReadOnly, def.IsReadOnly NOT working in either 2015 or 2014 but working in 2013 BoundToInstance = insBinding != null, BoundCategories = RawConvertSetToList <Category>(eleBinding.Categories).Select(c => c.Name).ToArray(), FromShared = shared, GUID = shared ? extDef.GUID.ToString() : string.Empty, Owner = shared ? extDef.OwnerGroup.Name : string.Empty, Visible = shared ? extDef.Visible : true, }; paramList.Add(param); } } return(paramList); }
public static Dictionary <string /*paramName*/, List <string> /*categoryNames*/> GetProjectParameterInfo(Document doc) { Dictionary <string, List <string> > projectParameters = new Dictionary <string, List <string> >(); try { BindingMap bindingMap = doc.ParameterBindings; DefinitionBindingMapIterator iterator = bindingMap.ForwardIterator(); while (iterator.MoveNext()) { Definition definition = iterator.Key as Definition; string paramName = definition.Name; ElementBinding elementBinding = iterator.Current as ElementBinding; List <string> categoryNames = new List <string>(); if (null != elementBinding) { foreach (Category category in elementBinding.Categories) { if (!string.IsNullOrEmpty(category.Name)) { categoryNames.Add(category.Name); } } } if (!projectParameters.ContainsKey(paramName)) { projectParameters.Add(paramName, categoryNames); } } } catch (Exception ex) { MessageBox.Show("Failed to get project parameter information.\n" + ex.Message, "Get Project Parameter Info", MessageBoxButton.OK, MessageBoxImage.Warning); } return(projectParameters); }
/// <summary> /// Method to retrieve filtered project parameters ID by category /// </summary> /// <param name="doc"></param> /// <param name="category"></param> /// <returns></returns> public static string[] ProjectParameters(Document doc, string categoryName) { List <string> parametersID = new List <string>(); BindingMap map = doc.ParameterBindings; DefinitionBindingMapIterator it = map.ForwardIterator(); it.Reset(); while (it.MoveNext()) { ElementBinding eleBinding = it.Current as ElementBinding; InstanceBinding insBinding = eleBinding as InstanceBinding; if (insBinding != null && IsInstBindingOfCategory(insBinding, categoryName)) { Definition def = it.Key; if (def != null) { ExternalDefinition extDef = def as ExternalDefinition; if (extDef != null) { string GUID = extDef.GUID.ToString(); parametersID.Add(GUID); } else { InternalDefinition intDef = def as InternalDefinition; string ID = intDef.Id.ToString(); parametersID.Add(ID); } } } } return(parametersID.ToArray()); }
/// <summary> /// Convert a Table ElementBinding to Database Type string (Upper) /// </summary> /// <param name="bind">ElementBindind to Convert</param> /// <param name="table">DataTableHandler for Special cases</param> /// <returns>Database Type string ToUpper</returns> protected virtual string GetDatabaseType(ElementBinding bind, DataTableHandler table) { string type = null; // Check Value Type if (bind.ValueType == typeof(char)) { type = "SMALLINT(5) UNSIGNED"; } else if (bind.ValueType == typeof(DateTime)) { type = "DATETIME"; } else if (bind.ValueType == typeof(sbyte)) { type = "TINYINT(3)"; } else if (bind.ValueType == typeof(short)) { type = "SMALLINT(6)"; } else if (bind.ValueType == typeof(int)) { type = "INT(11)"; } else if (bind.ValueType == typeof(long)) { type = "BIGINT(20)"; } else if (bind.ValueType == typeof(byte)) { type = "TINYINT(3) UNSIGNED"; } else if (bind.ValueType == typeof(ushort)) { type = "SMALLINT(5) UNSIGNED"; } else if (bind.ValueType == typeof(uint)) { type = "INT(10) UNSIGNED"; } else if (bind.ValueType == typeof(ulong)) { type = "BIGINT(20) UNSIGNED"; } else if (bind.ValueType == typeof(float)) { // Float Value have less precision than C# Single. type = "DOUBLE"; } else if (bind.ValueType == typeof(double)) { type = "DOUBLE"; } else if (bind.ValueType == typeof(bool)) { type = "TINYINT(1)"; } else if (bind.ValueType == typeof(string)) { if (bind.DataElement != null && bind.DataElement.Varchar > 0) { type = string.Format("VARCHAR({0})", bind.DataElement.Varchar); } else if (table.Table.PrimaryKey.Any(key => key.ColumnName.Equals(bind.ColumnName, StringComparison.OrdinalIgnoreCase)) || table.Table.Constraints.OfType <UniqueConstraint>().Any(cstrnt => cstrnt.Columns.Any(col => col.ColumnName.Equals(bind.ColumnName, StringComparison.OrdinalIgnoreCase))) || (table.Table.ExtendedProperties["INDEXES"] != null && (table.Table.ExtendedProperties["INDEXES"] as Dictionary <string, DataColumn[]>) .Any(kv => kv.Value.Any(col => col.ColumnName.Equals(bind.ColumnName, StringComparison.OrdinalIgnoreCase))))) { // If is in Primary Key Constraint or Unique Constraint or Index row, cast to Varchar. type = "VARCHAR(255)"; } else { type = "TEXT"; } } else { type = "BLOB"; } if (bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement) { if (bind.ValueType == typeof(ulong) || bind.ValueType == typeof(long)) { type = "BIGINT(20)"; } else { type = "INT(11)"; } } return(type); }
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); }
CollectEvent(object sender, CollectorEventArgs e) { // cast the sender object to the SnoopCollector we are expecting Collector snoopCollector = sender as Collector; if (snoopCollector == null) { Debug.Assert(false); // why did someone else send us the message? return; } // see if it is a type we are responsible for Parameter param = e.ObjToSnoop as Parameter; if (param != null) { Stream(snoopCollector.Data(), param); return; } Definition paramDef = e.ObjToSnoop as Definition; if (paramDef != null) { Stream(snoopCollector.Data(), paramDef); return; } DefinitionGroup defGroup = e.ObjToSnoop as DefinitionGroup; if (defGroup != null) { Stream(snoopCollector.Data(), defGroup); return; } DefinitionFile defFile = e.ObjToSnoop as DefinitionFile; if (defFile != null) { Stream(snoopCollector.Data(), defFile); return; } Binding binding = e.ObjToSnoop as Binding; if (binding != null) { Stream(snoopCollector.Data(), binding); return; } ElementBinding elemBind = e.ObjToSnoop as ElementBinding; if (elemBind != null) { Stream(snoopCollector.Data(), elemBind); return; } // no more in 2011? //ParameterListItem paramListItem = e.ObjToSnoop as ParameterListItem; //if (paramListItem != null) { // Stream(snoopCollector.Data(), paramListItem); // return; //} }
/// <summary> /// Convert a Table ElementBinding to Database Type string (Upper) /// </summary> /// <param name="bind">ElementBindind to Convert</param> /// <param name="table">DataTableHandler for Special cases</param> /// <returns>Database Type string ToUpper</returns> protected virtual string GetDatabaseType(ElementBinding bind, DataTableHandler table) { string type = null; // Check Value Type if (bind.ValueType == typeof(char)) { type = "UNSIGNED SMALLINT(5)"; } else if (bind.ValueType == typeof(sbyte)) { // override to prevent byte conversion type = "SMALLINT(3)"; } else if (bind.ValueType == typeof(short)) { type = "SMALLINT(6)"; } else if (bind.ValueType == typeof(int)) { type = "INT(11)"; } else if (bind.ValueType == typeof(long)) { type = "BIGINT(20)"; } else if (bind.ValueType == typeof(byte)) { type = "UNSIGNED TINYINT(3)"; } else if (bind.ValueType == typeof(ushort)) { type = "UNSIGNED SMALLINT(5)"; } else if (bind.ValueType == typeof(uint)) { type = "UNSIGNED INT(10)"; } else if (bind.ValueType == typeof(ulong)) { type = "UNSIGNED BIGINT(20)"; } else if (bind.ValueType == typeof(bool)) { type = "TINYINT(1)"; } else if (bind.ValueType == typeof(DateTime)) { type = "DATETIME"; } else if (bind.ValueType == typeof(float)) { type = "FLOAT"; } else if (bind.ValueType == typeof(double)) { type = "DOUBLE"; } else if (bind.ValueType == typeof(string)) { if (bind.DataElement != null && bind.DataElement.Varchar > 0) { type = string.Format("VARCHAR({0})", bind.DataElement.Varchar); } else if (table.Table.PrimaryKey.Any(key => key.ColumnName.Equals(bind.ColumnName, StringComparison.OrdinalIgnoreCase)) || table.Table.Constraints.OfType<UniqueConstraint>().Any(cstrnt => cstrnt.Columns.Any(col => col.ColumnName.Equals(bind.ColumnName, StringComparison.OrdinalIgnoreCase))) || (table.Table.ExtendedProperties["INDEXES"] != null && (table.Table.ExtendedProperties["INDEXES"] as Dictionary<string, DataColumn[]>) .Any(kv => kv.Value.Any(col => col.ColumnName.Equals(bind.ColumnName, StringComparison.OrdinalIgnoreCase))))) { // If is in Primary Key Constraint or Unique Constraint or Index row, cast to Varchar. type = "VARCHAR(255)"; } else { type = "TEXT"; } } else { type = "BLOB"; } if (bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement) type = "INTEGER"; return type; }
public static BindSharedParamResult BindSharedParam( Document doc, Category cat, string paramName, string grpName, ParameterType paramType, bool visible, bool instanceBinding) { try // generic { Application app = doc.Application; // This is needed already here to // store old ones for re-inserting CategorySet catSet = app.Create.NewCategorySet(); // Loop all Binding Definitions // IMPORTANT NOTE: Categories.Size is ALWAYS 1 !? // For multiple categories, there is really one // pair per each category, even though the // Definitions are the same... DefinitionBindingMapIterator iter = doc.ParameterBindings.ForwardIterator(); while (iter.MoveNext()) { Definition def = iter.Key; ElementBinding elemBind = (ElementBinding)iter.Current; // Got param name match if (paramName.Equals(def.Name, StringComparison.CurrentCultureIgnoreCase)) { // Check for category match - Size is always 1! if (elemBind.Categories.Contains(cat)) { // Check Param Type if (paramType != def.ParameterType) { return(BindSharedParamResult.eWrongParamType); } // Check Binding Type if (instanceBinding) { if (elemBind.GetType() != typeof(InstanceBinding)) { return(BindSharedParamResult.eWrongBindingType); } } else { if (elemBind.GetType() != typeof(TypeBinding)) { return(BindSharedParamResult.eWrongBindingType); } } // Check Visibility - cannot (not exposed) // If here, everything is fine, // ie already defined correctly return(BindSharedParamResult.eAlreadyBound); } // If here, no category match, hence must // store "other" cats for re-inserting else { foreach (Category catOld in elemBind.Categories) { catSet.Insert(catOld); // 1 only, but no index... } } } } // If here, there is no Binding Definition for // it, so make sure Param defined and then bind it! DefinitionFile defFile = GetOrCreateSharedParamsFile(app); DefinitionGroup defGrp = GetOrCreateSharedParamsGroup( defFile, grpName); Definition definition = GetOrCreateSharedParamDefinition( defGrp, paramType, paramName, visible); catSet.Insert(cat); InstanceBinding bind = null; if (instanceBinding) { bind = app.Create.NewInstanceBinding( catSet); } else { bind = app.Create.NewTypeBinding(catSet); } // There is another strange API "feature". // If param has EVER been bound in a project // (in above iter pairs or even if not there // but once deleted), Insert always fails!? // Must use .ReInsert in that case. // See also similar findings on this topic in: // http://thebuildingcoder.typepad.com/blog/2009/09/adding-a-category-to-a-parameter-binding.html // - the code-idiom below may be more generic: if (doc.ParameterBindings.Insert( definition, bind)) { return(BindSharedParamResult.eSuccessfullyBound); } else { if (doc.ParameterBindings.ReInsert( definition, bind)) { return(BindSharedParamResult.eSuccessfullyBound); } else { return(BindSharedParamResult.eFailed); } } } catch (Exception ex) { MessageBox.Show(string.Format( "Error in Binding Shared Param: {0}", ex.Message)); return(BindSharedParamResult.eFailed); } }
/// <summary> /// Get Database Column Definition for ElementBinding /// </summary> /// <param name="bind">ElementBinding for Column Definition</param> /// <param name="table">DataTableHanlder for Special cases</param> /// <returns>Column Definitnion string.</returns> protected virtual string GetColumnDefinition(ElementBinding bind, DataTableHandler table) { string type = GetDatabaseType(bind, table); string defaultDef = null; // Check for Default Value depending on Constraints and Type if (bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement) { defaultDef = "NOT NULL PRIMARY KEY AUTOINCREMENT"; } else if (bind.DataElement != null && bind.DataElement.AllowDbNull) { defaultDef = "DEFAULT NULL"; } else if (bind.ValueType == typeof(DateTime)) { defaultDef = "NOT NULL DEFAULT '2000-01-01 00:00:00'"; } else { defaultDef = "NOT NULL"; } // Force Case Insensitive Text Field to Match MySQL Behavior if (bind.ValueType == typeof(string)) defaultDef = string.Format("{0} {1}", defaultDef, "COLLATE NOCASE"); return string.Format("`{0}` {1} {2}", bind.ColumnName, type, defaultDef); }
private void 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; } }
/// <summary> /// Добавить привязку к категории для параметра проекта /// </summary> public static BindSharedParamResult BindSharedParam(Document doc, Element elem, string paramName, Definition definition) { try { Application app = doc.Application; //собираю уже добавленные категории для повторной вставки и добавления новой категории 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; if (!paramName.Equals(def.Name)) { continue; } ElementBinding elemBind = (ElementBinding)iter.Current; // Check for category match - Size is always 1! // If here, no category match, hence must // store "other" cats for re-inserting 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! Category cat = elem.Category; catSet.Insert(cat); InstanceBinding bind = app.Create.NewInstanceBinding(catSet); //используем Insert или ReInsert, что сработает 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) { Autodesk.Revit.UI.TaskDialog.Show("Error", string.Format( "Error in Binding Shared Param: {0}", ex.Message)); return(BindSharedParamResult.eFailed); } }
/// <summary> /// Set Value to DataObject Field according to ElementBinding /// Override for SQLite to Handle some Specific Case (Unsigned Int64...) /// </summary> /// <param name="obj">DataObject to Fill</param> /// <param name="bind">ElementBinding for the targeted Member</param> /// <param name="value">Object Value to Fill</param> protected override void DatabaseSetValue(DataObject obj, ElementBinding bind, object value) { try { if (value != null && bind.ValueType == typeof(ulong)) { bind.SetValue(obj, unchecked((ulong)Convert.ToInt64(value))); return; } } catch (Exception e) { if (Log.IsErrorEnabled) Log.ErrorFormat("{0}: {1} = {2} doesnt fit to {3}\n{4}", obj.TableName, bind.ColumnName, value.GetType().FullName, bind.ValueType, e); } base.DatabaseSetValue(obj, bind, value); }
public VertexAttributeAttribute(ElementBinding elementBinding, ElementType elementType, int typeCount) { this.elementBinding = elementBinding; this.elementType = elementType; this.typeCount = typeCount; }
/// <summary> /// Command Entry Point /// </summary> /// <param name="commandData"></param> /// <param name="message"></param> /// <param name="elements"></param> /// <returns></returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { // Document Document m_doc = commandData.Application.ActiveUIDocument.Document; // Session Guid string m_guid = Guid.NewGuid().ToString(); //// New Schedules //List<ViewSchedule> m_schedules = new List<ViewSchedule>(); //// Project Information //// Wires //// Roads //// Rebar Shape //// Areas //// Materials //// Shaft Openings //// Views //// Sheets //// Start a New Transaction //using (Transaction t = new Transaction(m_doc)) //{ // if (t.Start("Not Saved") == TransactionStatus.Started) // { // try // { // // Find Categories that Support Custom Parameter Bindings // foreach (Category x in m_doc.Settings.Categories) // { // if (x.AllowsBoundParameters) // { // try // { // // New Schedule // ViewSchedule m_vs = ViewSchedule.CreateSchedule(m_doc, x.Id); // m_vs.Name = x.Name; // m_schedules.Add(m_vs); // if (x.Id.IntegerValue == (int)BuiltInCategory.OST_Rooms) // { // foreach (SchedulableField sf in m_vs.Definition.GetSchedulableFields()) // { // m_vs.Definition.AddField(sf); // //// Shared Parameters will have a Positive ID // //if (sf.ParameterId.IntegerValue > 0) // //{ // // Element m_elem = m_doc.GetElement(sf.ParameterId); // //} // } // } // } // catch { } // } // } // // Commit // t.Commit(); // } // catch { } // } //} // Show the Progressbar Form form_Main m_dlg = new form_Main(m_doc.ParameterBindings.Size + 1); m_dlg.Show(); BindingMap m_map = m_doc.ParameterBindings; try { // Iterate DefinitionBindingMapIterator m_iter = m_map.ForwardIterator(); while (m_iter.MoveNext()) { ElementBinding m_eb = m_iter.Current as ElementBinding; Definition m_def = m_iter.Key; try { ExternalDefinition m_extDev = m_def as ExternalDefinition; if (m_extDev != null) { string m_todo = string.Empty; } } catch { } //if (m_eb != null) //{ // CategorySet m_set = m_eb.Categories; //} } } catch { } // Success return(Result.Succeeded); } catch (Exception ex) { // Failure message = ex.Message; return(Result.Failed); } }
public static bool AddProjectParameter(this Document document, ExternalDefinitionCreationOptions externalDefinitionCreationOptions, IEnumerable <BuiltInCategory> builtInCategories, bool instance, BuiltInParameterGroup builtInParameterGroup) { if (document == null || externalDefinitionCreationOptions == null || builtInCategories == null) { return(false); } string name = externalDefinitionCreationOptions.Name; if (string.IsNullOrWhiteSpace(name)) { return(false); } CategorySet categorySet = Create.CategorySet(document, builtInCategories); if (categorySet == null || categorySet.Size == 0) { return(false); } ElementBinding elementBinding = null; if (Query.TryGetElementBinding(document, externalDefinitionCreationOptions.Name, out InternalDefinition internalDefinition, out elementBinding)) { return(false); } Autodesk.Revit.ApplicationServices.Application application = new UIDocument(document).Application.Application; bool result = false; string path = System.IO.Path.GetTempFileName(); try { using (SharedParameterFileWrapper sharedParameterFileWrapper = new SharedParameterFileWrapper(application)) { Definition definition = sharedParameterFileWrapper.Create(System.IO.Path.GetRandomFileName(), externalDefinitionCreationOptions); if (definition != null) { if (instance) { elementBinding = application.Create.NewInstanceBinding(categorySet); } else { elementBinding = application.Create.NewTypeBinding(categorySet); } if (elementBinding != null) { result = document.ParameterBindings.Insert(definition, elementBinding, builtInParameterGroup); } } } } catch (Exception exception) { } finally { if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } return(result); }
/// <summary> /// Get Database Column Definition for ElementBinding /// </summary> /// <param name="bind">ElementBinding for Column Definition</param> /// <param name="table">DataTableHanlder for Special cases</param> /// <returns>Column Definitnion string.</returns> protected virtual string GetColumnDefinition(ElementBinding bind, DataTableHandler table) { string type = GetDatabaseType(bind, table); string defaultDef = null; // Check for Default Value depending on Constraints and Type if (bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement) { defaultDef = "NOT NULL AUTO_INCREMENT"; } else if (bind.DataElement != null && bind.DataElement.AllowDbNull) { defaultDef = "DEFAULT NULL"; } else if (bind.ValueType == typeof(DateTime)) { defaultDef = "NOT NULL DEFAULT '2000-01-01 00:00:00'"; } else { defaultDef = "NOT NULL"; } return string.Format("`{0}` {1} {2}", bind.ColumnName, type, defaultDef); }