Example #1
0
        public ParameterData(
            BuiltInParameter bip,
            Parameter parameter,
            string valueStringOrElementDescription,
            bool containedInCollection,
            /*
            * Edited by Chekalin Victor 13.12.2012
            */
            string parameterName)
        {
            _enum = bip;
            _parameter = parameter;
            /*
             * Edited by Chekalin Victor 13.12.2012
             */
            _parameterName = parameterName;

            ValueString = valueStringOrElementDescription;
            Value = GetValue;

            Definition d = _parameter.Definition;

            ParameterGroup = d.ParameterGroup.ToString();
            GroupName = LabelUtils.GetLabelFor(d.ParameterGroup);
            ContainedInCollection = containedInCollection ? "Y" : "N";
        }
Example #2
0
 /// <summary>
 /// Convert FilterRule to our custom FilterRuleBuilder which will be displayed in form controls  
 /// </summary>
 /// <param name="param">Parameter to which the FilterRule is applied.</param>
 /// <param name="rule">FilterRule to be converted.</param>
 /// <returns>Custom FilterRuleBuilder data converted from FilterRule</returns>
 public static FilterRuleBuilder CreateFilterRuleBuilder(BuiltInParameter param, FilterRule rule)
 {
     // Maybe FilterRule is inverse rule, we need to find its inner rule(FilterValueRule)
     // Note that the rule may be inversed more than once.
     bool inverted = false;
     FilterRule innerRule = ReflectToInnerRule(rule, out inverted);
     if (innerRule is FilterStringRule)
     {
         FilterStringRule strRule = innerRule as FilterStringRule;
         FilterStringRuleEvaluator evaluator = strRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), strRule.RuleString, strRule.CaseSensitive);
     }
     else if (innerRule is FilterDoubleRule)
     {
         FilterDoubleRule dbRule = innerRule as FilterDoubleRule;
         FilterNumericRuleEvaluator evaluator = dbRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), dbRule.RuleValue, dbRule.Epsilon);
     }
     else if (innerRule is FilterIntegerRule)
     {
         FilterIntegerRule intRule = innerRule as FilterIntegerRule;
         FilterNumericRuleEvaluator evaluator = intRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), intRule.RuleValue);
     }
     else if (innerRule is FilterElementIdRule)
     {
         FilterElementIdRule idRule = innerRule as FilterElementIdRule;
         FilterNumericRuleEvaluator evaluator = idRule.GetEvaluator();
         return new FilterRuleBuilder(param, GetEvaluatorCriteriaName(evaluator, inverted), idRule.RuleValue);
     }
     //
     // for other rule, not supported yet
     throw new System.NotImplementedException("The filter rule is not recognizable and supported yet!");
 }
Example #3
0
        /// <summary>
        /// set certain parameter of given element to int value
        /// </summary>
        /// <param name="elem">given element</param>
        /// <param name="paraIndex">BuiltInParameter</param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SetParaInt(Element elem, BuiltInParameter paraIndex, int value)
        {
            Parameter para = elem.get_Parameter(paraIndex);
            if (null == para)
            {
                return false;
            }

            para.Set(value);
            return true;
        }
        /// <summary>
        /// Create a Frequency measure property from the element's or type's parameter.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="elem">The Element.</param>
        /// <param name="revitParameterName">The name of the parameter.</param>
        /// <param name="revitBuiltInParam">The built in parameter to use, if revitParameterName isn't found.</param>
        /// <param name="ifcPropertyName">The name of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created property handle.</returns>
        public static IFCAnyHandle CreateFrequencyPropertyFromElementOrSymbol(IFCFile file, ExporterIFC exporterIFC, Element elem,
            string revitParameterName, BuiltInParameter revitBuiltInParam, string ifcPropertyName, PropertyValueType valueType)
        {
            IFCAnyHandle propHnd = CreateFrequencyPropertyFromElement(file, exporterIFC, elem, revitParameterName, ifcPropertyName, valueType);
            if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
                return propHnd;

            if (revitBuiltInParam != BuiltInParameter.INVALID)
            {
                string builtInParamName = LabelUtils.GetLabelFor(revitBuiltInParam);
                propHnd = CreateFrequencyPropertyFromElement(file, exporterIFC, elem, builtInParamName, ifcPropertyName, valueType);
                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
                    return propHnd;
            }

            // For Symbol
            Document document = elem.Document;
            ElementId typeId = elem.GetTypeId();
            Element elemType = document.GetElement(typeId);
            if (elemType != null)
                return CreateFrequencyPropertyFromElementOrSymbol(file, exporterIFC, elemType, revitParameterName, revitBuiltInParam, ifcPropertyName, valueType);
            else
                return null;
        }
Example #5
0
        /// <summary>
        /// Create a positive length property from the element's or type's parameter.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="elem">The Element.</param>
        /// <param name="revitParameterName">The name of the parameter.</param>
        /// <param name="revitBuiltInParam">The optional built-in parameter.</param>
        /// <param name="ifcPropertyName">The name of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created property handle.</returns>
        public static IFCAnyHandle CreatePositiveLengthMeasurePropertyFromElementOrSymbol(IFCFile file, ExporterIFC exporterIFC, Element elem,
            string revitParameterName, BuiltInParameter revitBuiltInParam, string ifcPropertyName, PropertyValueType valueType)
        {
            double propertyValue;
            if (ParameterUtil.GetDoubleValueFromElement(elem, revitParameterName, out propertyValue))
            {
                propertyValue *= exporterIFC.LinearScale;
                return CreatePositiveLengthMeasureProperty(file, ifcPropertyName, propertyValue, valueType);
            }

            if (revitBuiltInParam != BuiltInParameter.INVALID)
            {
                string builtInParamName = LabelUtils.GetLabelFor(revitBuiltInParam);
                IFCAnyHandle propHnd = CreatePositiveLengthMeasurePropertyFromElement(file, exporterIFC, elem, builtInParamName, ifcPropertyName, valueType);
                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
                    return propHnd;
            }

            // For Symbol
            Document document = elem.Document;
            ElementId typeId = elem.GetTypeId();
            Element elemType = document.GetElement(typeId);
            if (elemType != null)
                return CreatePositiveLengthMeasurePropertyFromElement(file, exporterIFC, elemType, revitParameterName, ifcPropertyName, valueType);
            else
                return null;
        }
Example #6
0
        /// <summary>
        /// find a parameter according to the parameter's name
        /// </summary>
        /// <param name="element">the host object of the parameter</param>
        /// <param name="paraIndex">parameter index</param>
        /// <param name="value">the value of the parameter with Autodesk.Revit.DB.ElementId type</param>
        /// <returns>if find the parameter return true</returns>
        public static bool SetParameter(Element element, 
          BuiltInParameter paraIndex, ref Autodesk.Revit.DB.ElementId value)
        {
            Parameter parameter = element.get_Parameter(paraIndex);
             if (null == parameter)
             {
            return false;
             }

             if (!parameter.IsReadOnly)
             {
            StorageType parameterType = parameter.StorageType;
            if (StorageType.ElementId != parameterType)
            {
               throw new Exception("The types of value and parameter are different!");
            }
            parameter.Set(value);
            return true;
             }

             return false;
        }
Example #7
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Open source project

            Document docHasFamily = app.OpenDocumentFile(
                _source_project_path);

            // Find system family to copy, e.g. using a named wall type

            WallType wallType = null;

            //WallTypeSet wallTypes = docHasFamily.WallTypes; // 2013

            FilteredElementCollector wallTypes
                = new FilteredElementCollector(docHasFamily) // 2014
                  .OfClass(typeof(WallType));

            int i = 0;

            foreach (WallType wt in wallTypes)
            {
                string name = wt.Name;

                Debug.Print("  {0} {1}", ++i, name);

                if (name.Equals(_wall_type_name))
                {
                    wallType = wt;
                    break;
                }
            }

            if (null == wallType)
            {
                message = string.Format(
                    "Cannot find source wall type '{0}'"
                    + " in source document '{1}'. ",
                    _wall_type_name, _source_project_path);

                return(Result.Failed);
            }

            // Create a new wall type in current document

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Transfer Wall Type");

                WallType newWallType = null;

                //WallTypeSet wallTypes = doc.WallTypes; // 2013

                wallTypes = new FilteredElementCollector(doc)
                            .OfClass(typeof(WallType)); // 2014

                foreach (WallType wt in wallTypes)
                {
                    if (wt.Kind == wallType.Kind)
                    {
                        newWallType = wt.Duplicate(_wall_type_name)
                                      as WallType;

                        Debug.Print(string.Format(
                                        "New wall type '{0}' created.",
                                        _wall_type_name));

                        break;
                    }
                }

                // Assign parameter values from source wall type:

#if COPY_INDIVIDUAL_PARAMETER_VALUE
                // Example: individually copy the "Function" parameter value:

                BuiltInParameter bip      = BuiltInParameter.FUNCTION_PARAM;
                string           function = wallType.get_Parameter(bip).AsString();
                Parameter        p        = newWallType.get_Parameter(bip);
                p.Set(function);
#endif // COPY_INDIVIDUAL_PARAMETER_VALUE

                Parameter p = null;

                foreach (Parameter p2 in newWallType.Parameters)
                {
                    Definition d = p2.Definition;

                    if (p2.IsReadOnly)
                    {
                        Debug.Print(string.Format(
                                        "Parameter '{0}' is read-only.", d.Name));
                    }
                    else
                    {
                        p = wallType.get_Parameter(d);

                        if (null == p)
                        {
                            Debug.Print(string.Format(
                                            "Parameter '{0}' not found on source wall type.",
                                            d.Name));
                        }
                        else
                        {
                            if (p.StorageType == StorageType.ElementId)
                            {
                                // Here you have to find the corresponding
                                // element in the target document.

                                Debug.Print(string.Format(
                                                "Parameter '{0}' is an element id.",
                                                d.Name));
                            }
                            else
                            {
                                if (p.StorageType == StorageType.Double)
                                {
                                    p2.Set(p.AsDouble());
                                }
                                else if (p.StorageType == StorageType.String)
                                {
                                    p2.Set(p.AsString());
                                }
                                else if (p.StorageType == StorageType.Integer)
                                {
                                    p2.Set(p.AsInteger());
                                }
                                Debug.Print(string.Format(
                                                "Parameter '{0}' copied.", d.Name));
                            }
                        }
                    }

                    // Note:
                    // If a shared parameter parameter is attached,
                    // you need to create the shared parameter first,
                    // then copy the parameter value.
                }

                // If the system family type has some other properties,
                // you need to copy them as well here. Reflection can
                // be used to determine the available properties.

                MemberInfo[] memberInfos = newWallType.GetType()
                                           .GetMembers(BindingFlags.GetProperty);

                foreach (MemberInfo m in memberInfos)
                {
                    // Copy the writable property values here.
                    // As there are no property writable for
                    // Walltype, I ignore this process here.
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
        /// <summary>
        /// Sets string value of a built-in parameter of an element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built-in parameter.</param>
        /// <param name="propertyValue">The property value.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when element is null.</exception>
        /// <exception cref="System.ArgumentException">Thrown when builtInParameter in invalid.</exception>
        public static void SetStringParameter(Element element, BuiltInParameter builtInParameter, string propertyValue)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            if (builtInParameter == BuiltInParameter.INVALID)
                throw new ArgumentException("BuiltInParameter is INVALID", "builtInParameter");

            Parameter parameter = element.get_Parameter(builtInParameter);
            if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String)
            {
                parameter.SetValueString(propertyValue);
                return;
            }

            ElementId parameterId = new ElementId(builtInParameter);
            ExporterIFCUtils.AddValueString(element, parameterId, propertyValue);
        }
 private void SetGUIDParameter(Element element, BuiltInParameter builtInParameter, string guidValue)
 {
     Parameter parameter = element.get_Parameter(builtInParameter);
     if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String)
     {
         parameter.SetValueString(guidValue);
     }
     else
     {
         ElementId parameterId = new ElementId(builtInParameter);
         ExporterIFCUtils.AddValueString(element, parameterId, guidValue);
     }
 }
        static private string CreateGUIDBase(Element element, BuiltInParameter parameterName, out bool shouldStore)
        {
            shouldStore = false;
            string ifcGUID = null;
            
            if (ExporterCacheManager.ExportOptionsCache.GUIDOptions.AllowGUIDParameterOverride)
                ParameterUtil.GetStringValueFromElement(element, parameterName, out ifcGUID);
            if (String.IsNullOrEmpty(ifcGUID))
            {
                System.Guid guid = ExportUtils.GetExportId(element.Document, element.Id);
                ifcGUID = ConvertToIFCGuid(guid);
                shouldStore = true;
            }

            return ifcGUID;
        }
Example #11
0
 /// <summary>
 /// Check to see if rule for this parameter exists or not
 /// </summary>
 /// <param name="param">Parameter to be checked.</param>
 /// <returns>True if this parameter already has filter rule, otherwise false.</returns>
 bool ParameterAlreadyExist(BuiltInParameter param)
 {
     if (m_currentFilterData == null || m_currentFilterData.RuleData.Count == 0)
         return false;
     for (int ruleNo = 0; ruleNo < m_currentFilterData.RuleData.Count; ruleNo++)
     {
         if (m_currentFilterData.RuleData[ruleNo].Parameter == param)
             return true;
     }
     return false;
 }
Example #12
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            Autodesk.Revit.Creation.Application createApp
                = app.Application.Create;

            Autodesk.Revit.Creation.Document createDoc
                = doc.Create;

            // Determine the wall endpoints:

            double length = 5 * MeterToFeet;

            XYZ [] pts = new XYZ[2];

            pts[0] = XYZ.Zero;
            pts[1] = new XYZ(length, 0, 0);

            // Determine the levels where
            // the wall will be located:

            Level levelBottom = null;
            Level levelTop    = null;

            if (!GetBottomAndTopLevels(doc,
                                       ref levelBottom, ref levelTop))
            {
                message = "Unable to determine "
                          + "wall bottom and top levels";

                return(Result.Failed);
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Wall, Door and Tag");

                // Create a wall:

                BuiltInParameter topLevelParam
                    = BuiltInParameter.WALL_HEIGHT_TYPE;

                ElementId topLevelId = levelTop.Id;

                //Line line = createApp.NewLineBound( pts[0], pts[1] ); // 2013
                Line line = Line.CreateBound(pts[0], pts[1]); // 2014

                //Wall wall = createDoc.NewWall( // 2012
                //  line, levelBottom, false );

                Wall wall = Wall.Create( // 2013
                    doc, line, levelBottom.Id, false);

                Parameter param = wall.get_Parameter(
                    topLevelParam);

                param.Set(topLevelId);

                // Determine wall thickness for tag
                // offset and profile growth:

                //double wallThickness = wall.WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011

                double wallThickness = wall.WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012

                // Add door to wall;
                // note that the NewFamilyInstance method
                // does not automatically add a door tag,
                // like the UI command does:

                FamilySymbol doorSymbol = GetFirstFamilySymbol(
                    doc, BuiltInCategory.OST_Doors);

                if (null == doorSymbol)
                {
                    message = "No door symbol found.";
                    return(Result.Failed);
                }

                XYZ midpoint = Util.Midpoint(pts[0], pts[1]);

                FamilyInstance door = createDoc
                                      .NewFamilyInstance(
                    midpoint, doorSymbol, wall, levelBottom,
                    StructuralType.NonStructural);

                // Create door tag:

                View view = doc.ActiveView;

                double tagOffset = 3 * wallThickness;

                midpoint += tagOffset * XYZ.BasisY;

                // 2011: TagOrientation.TAG_HORIZONTAL

                //IndependentTag tag = createDoc.NewTag(
                //  view, door, false, TagMode.TM_ADDBY_CATEGORY,
                //  TagOrientation.Horizontal, midpoint ); // 2012

                IndependentTag tag = IndependentTag.Create(
                    doc, view.Id, new Reference(door),
                    false, TagMode.TM_ADDBY_CATEGORY,
                    TagOrientation.Horizontal, midpoint); // 2018

                // Create and assign new door tag type:

                FamilySymbol doorTagType
                    = GetFirstFamilySymbol(
                          doc, BuiltInCategory.OST_DoorTags);

                doorTagType = doorTagType.Duplicate(
                    "New door tag type") as FamilySymbol;

                tag.ChangeTypeId(doorTagType.Id);

                // Demonstrate changing name of
                // family instance and family symbol:

                door.Name        = door.Name + " modified";
                door.Symbol.Name = door.Symbol.Name + " modified";

                t.Commit();
            }

            return(Result.Succeeded);
        }
Example #13
0
 public PropertySetEntry(PropertyType propertyType, string propertyName, BuiltInParameter builtInParameter)
     : base(propertyName, new PropertySetEntryMap(propertyName) { RevitBuiltInParameter = builtInParameter })
 {
     PropertyType = propertyType;
 }
Example #14
0
 static private void AddEntry(string propertyName, BuiltInParameter revitParameter)
 {
     m_BuiltInGeneralParameterMapping.Add(propertyName, revitParameter);
 }
Example #15
0
 static private void AddEntry(string psetName, string propertyName, BuiltInParameter revitParameter)
 {
     m_BuiltInSpecificParameterMapping.Add(new KeyValuePair <string, string>(psetName, propertyName), revitParameter);
 }
Example #16
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;


            // Open source project
            Document docHasFamily = app.OpenDocumentFile(_source_project_path);

            // Find system family to copy, e.g. using a named wall type
            WallType _selectedWallType = null;

            FilteredElementCollector wallTypes
                = new FilteredElementCollector(docHasFamily) // 2014
                  .OfClass(typeof(WallType));

            int i = 0;



            foreach (WallType wt in wallTypes)
            {
                //Add the wall type to the list
                m_data.Add(wt.Name);
            }

            //show the form and get a value back from it
            //See this page for example: https://stackoverflow.com/questions/5233502/how-to-return-a-value-from-a-form-in-c
            using (var f = new frmListDialog(m_data))
            {
                var result = f.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    _selectedWallTypeName = f.ReturnValue1; //values preserved after close

                    //loop thru and find the wall type the matches the name
                    foreach (WallType wt in wallTypes)
                    {
                        if (wt.Name == _selectedWallTypeName)
                        {
                            //if its a match then...
                            _selectedWallType = wt;
                            //_selectedWallTypeName = wt.Name;
                        }
                    }
                }
            }



            //foreach( WallType wt in wallTypes )
            //{
            //  string name = wt.Name;

            //  Debug.Print( "  {0} {1}", ++i, name );

            //  if( name.Equals( _selectedWallTypeName ) )
            //  {
            //    _selectedWallType = wt;
            //    break;
            //  }
            //}

            //if( null == _selectedWallType )
            //{
            //  message = string.Format(
            //    "Cannot find source wall type '{0}'"
            //    + " in source document '{1}'. ",
            //    _selectedWallTypeName, _source_project_path );

            //  return Result.Failed;
            //}



            // Create a new wall type in current document

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Transfer Wall Type");

                WallType newWallType = null;

                wallTypes = new FilteredElementCollector(doc).OfClass(typeof(WallType)); // 2014

                foreach (WallType wt in wallTypes)
                {
                    if (wt.Kind == _selectedWallType.Kind)
                    {
                        newWallType = wt.Duplicate(_selectedWallTypeName) as WallType;

                        TaskDialog.Show("New wall type '{0}' created.", "Wall type " + _selectedWallTypeName + "created.");

                        break;
                    }
                }

                // Assign parameter values from source wall type:

#if COPY_INDIVIDUAL_PARAMETER_VALUE
                // Example: individually copy the "Function" parameter value:

                BuiltInParameter bip      = BuiltInParameter.FUNCTION_PARAM;
                string           function = wallType.get_Parameter(bip).AsString();
                Parameter        p        = newWallType.get_Parameter(bip);
                p.Set(function);
#endif // COPY_INDIVIDUAL_PARAMETER_VALUE

                Parameter p = null;

                foreach (Parameter p2 in newWallType.Parameters)
                {
                    Definition d = p2.Definition;

                    if (p2.IsReadOnly)
                    {
                        Debug.Print(string.Format(
                                        "Parameter '{0}' is read-only.", d.Name));
                    }
                    else
                    {
                        p = _selectedWallType.get_Parameter(d);

                        if (null == p)
                        {
                            Debug.Print(string.Format(
                                            "Parameter '{0}' not found on source wall type.",
                                            d.Name));
                        }
                        else
                        {
                            if (p.StorageType == StorageType.ElementId)
                            {
                                // Here you have to find the corresponding
                                // element in the target document.

                                Debug.Print(string.Format(
                                                "Parameter '{0}' is an element id.",
                                                d.Name));
                            }
                            else
                            {
                                if (p.StorageType == StorageType.Double)
                                {
                                    p2.Set(p.AsDouble());
                                }
                                else if (p.StorageType == StorageType.String)
                                {
                                    p2.Set(p.AsString());
                                }
                                else if (p.StorageType == StorageType.Integer)
                                {
                                    p2.Set(p.AsInteger());
                                }


                                Debug.Print(string.Format(
                                                "Parameter '{0}' copied.", d.Name));
                            }
                        }
                    }

                    // Note:
                    // If a shared parameter parameter is attached,
                    // you need to create the shared parameter first,
                    // then copy the parameter value.
                }

                // If the system family type has some other properties,
                // you need to copy them as well here. Reflection can
                // be used to determine the available properties.

                MemberInfo[] memberInfos = newWallType.GetType()
                                           .GetMembers(BindingFlags.GetProperty);

                foreach (MemberInfo m in memberInfos)
                {
                    // Copy the writable property values here.
                    // As there are no property writable for
                    // Walltype, I ignore this process here.
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
Example #17
0
        /// <summary>
        /// Gets element id value from parameter of an element or its element type.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built in parameter.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <returns>The parameter, or null if not found.</returns>
        public static Parameter GetElementIdValueFromElementOrSymbol(Element element, BuiltInParameter builtInParameter, out ElementId propertyValue)
        {
            Parameter parameter = GetElementIdValueFromElement(element, builtInParameter, out propertyValue);

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

            Document  document = element.Document;
            ElementId typeId   = element.GetTypeId();

            Element elemType = document.GetElement(typeId);

            if (elemType != null)
            {
                return(GetElementIdValueFromElement(elemType, builtInParameter, out propertyValue));
            }

            return(null);
        }
Example #18
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            try
            {
                WaitCursor    waitCursor = new WaitCursor();
                UIApplication app        = commandData.Application;
                Document      doc        = app.ActiveUIDocument.Document;
                Autodesk.Revit.Creation.Application createApp = app.Application.Create;
                Autodesk.Revit.Creation.Document    createDoc = doc.Create;

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Create Little House");

                    // Determine the four corners of the rectangular house:

                    double width = 7 * LabConstants.MeterToFeet;
                    double depth = 4 * LabConstants.MeterToFeet;

                    List <XYZ> corners = new List <XYZ>(4);

                    corners.Add(XYZ.Zero);
                    corners.Add(new XYZ(width, 0, 0));
                    corners.Add(new XYZ(width, depth, 0));
                    corners.Add(new XYZ(0, depth, 0));

                    #region Test creating two levels
#if CREATE_TWO_LEVELS
                    Level          levelBottom = null;
                    Level          levelMiddle = null;
                    Level          levelTop    = null;
                    List <Element> levels      = new List <Element>();

                    Filter filterType
                        = createApp.Filter.NewTypeFilter(
                              typeof(Level));

                    doc.get_Elements(filterType, levels);
                    foreach (Element e in levels)
                    {
                        if (null == levelBottom)
                        {
                            levelBottom = e as Level;
                        }
                        else if (null == levelMiddle)
                        {
                            levelMiddle = e as Level;
                        }
                        else if (null == levelTop)
                        {
                            levelTop = e as Level;
                        }
                        else
                        {
                            break;
                        }
                    }

                    BuiltInParameter topLevelParam
                        = BuiltInParameter.WALL_HEIGHT_TYPE;

                    Line      line;
                    Wall      wall;
                    Parameter param;

                    ElementId   topId = levelMiddle.Id;
                    List <Wall> walls = new List <Wall>(8);
                    for (int i = 0; i < 4; ++i)
                    {
                        line = createApp.NewLineBound(
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        wall = createDoc.NewWall(
                            line, levelBottom, false);

                        param = wall.get_Parameter(topLevelParam);
                        param.Set(ref topId);
                        walls.Add(wall);
                    }

                    topId = levelTop.Id;
                    for (int i = 0; i < 4; ++i)
                    {
                        line = createApp.NewLineBound(
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        wall = createDoc.NewWall(
                            line, levelMiddle, false);

                        param = wall.get_Parameter(topLevelParam);
                        param.Set(ref topId);
                        walls.Add(wall);
                    }

                    List <Element> doorSymbols
                        = LabUtils.GetAllFamilySymbols(
                              app, BuiltInCategory.OST_Doors);

                    Debug.Assert(
                        0 < doorSymbols.Count,
                        "expected at least one door symbol"
                        + " to be loaded into project");

                    FamilySymbol door
                        = doorSymbols[0] as FamilySymbol;

                    XYZ midpoint = LabUtils.Midpoint(
                        corners[0], corners[1]);

                    FamilyInstance inst0
                        = createDoc.NewFamilyInstance(
                              midpoint, door, walls[0], levelBottom,
                              StructuralType.NonStructural);

                    midpoint.Z = levelMiddle.Elevation;

                    FamilyInstance inst1
                        = createDoc.NewFamilyInstance(
                              midpoint, door, walls[4], levelMiddle,
                              StructuralType.NonStructural);
#endif // CREATE_TWO_LEVELS
                    #endregion // Test creating two levels

                    // Determine the levels where the walls will be located:

                    Level levelBottom = null;
                    Level levelTop    = null;

                    if (!LabUtils.GetBottomAndTopLevels(doc, ref levelBottom, ref levelTop))
                    {
                        message = "Unable to determine wall bottom and top levels";
                        return(Result.Failed);
                    }
                    Debug.Print(string.Format("Drawing walls on '{0}' up to '{1}'",
                                              levelBottom.Name, levelTop.Name));

                    // Create the walls:

                    BuiltInParameter topLevelParam = BuiltInParameter.WALL_HEIGHT_TYPE;
                    ElementId        levelBottomId = levelBottom.Id;
                    ElementId        topLevelId    = levelTop.Id;
                    List <Wall>      walls         = new List <Wall>(4);
                    for (int i = 0; i < 4; ++i)
                    {
                        Line line = Line.CreateBound(corners[i], corners[3 == i ? 0 : i + 1]);
                        //Wall wall = createDoc.NewWall( line, levelBottom, false ); // 2012
                        Wall      wall  = Wall.Create(doc, line, levelBottomId, false); // 2013
                        Parameter param = wall.get_Parameter(topLevelParam);
                        param.Set(topLevelId);
                        walls.Add(wall);
                    }

                    // Determine wall thickness for tag offset and profile growth:

                    //double wallThickness = walls[0].WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011
                    //double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012
                    double wallThickness = walls[0].WallType.Width; // simpler and more direct property available in 2012

                    // Add door and windows to the first wall;
                    // note that the NewFamilyInstance() api method does not automatically add door
                    // and window tags, like the ui command does. we add tags here by making additional calls
                    // to NewTag():

                    FamilySymbol door = LabUtils.GetFirstFamilySymbol(doc, BuiltInCategory.OST_Doors);
                    if (null == door)
                    {
                        LabUtils.InfoMsg("No door symbol found.");
                        return(Result.Failed);
                    }
                    FamilySymbol window = LabUtils.GetFirstFamilySymbol(
                        doc, BuiltInCategory.OST_Windows);

                    if (null == window)
                    {
                        LabUtils.InfoMsg("No window symbol found.");
                        return(Result.Failed);
                    }

                    XYZ    midpoint  = LabUtils.Midpoint(corners[0], corners[1]);
                    XYZ    p         = LabUtils.Midpoint(corners[0], midpoint);
                    XYZ    q         = LabUtils.Midpoint(midpoint, corners[1]);
                    double tagOffset = 3 * wallThickness;

                    //double windowHeight = 1 * LabConstants.MeterToFeet;
                    double windowHeight = levelBottom.Elevation + 0.3 * (
                        levelTop.Elevation - levelBottom.Elevation);

                    p = new XYZ(p.X, p.Y, windowHeight);
                    q = new XYZ(q.X, q.Y, windowHeight);
                    View view = doc.ActiveView;

                    door.Activate(); // 2016

                    FamilyInstance inst = createDoc.NewFamilyInstance(
                        midpoint, door, walls[0], levelBottom, StructuralType.NonStructural);

                    midpoint += tagOffset * XYZ.BasisY;
                    IndependentTag tag = createDoc.NewTag(
                        view, inst, false, TagMode.TM_ADDBY_CATEGORY,
                        TagOrientation.Horizontal, midpoint);

                    window.Activate(); // 2016

                    inst = createDoc.NewFamilyInstance(p, window,
                                                       walls[0], levelBottom, StructuralType.NonStructural);

                    p  += tagOffset * XYZ.BasisY;
                    tag = createDoc.NewTag(view, inst, false,
                                           TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, p);

                    inst = createDoc.NewFamilyInstance(q, window, walls[0],
                                                       levelBottom, StructuralType.NonStructural);

                    q += tagOffset * XYZ.BasisY;

                    //tag = createDoc.NewTag( view, inst, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.TAG_HORIZONTAL, q ); // 2011
                    tag = createDoc.NewTag(view, inst, false,
                                           TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, q); // 2012

                    // Grow the profile out by half the wall thickness,
                    // so the floor and roof do not stop halfway through the wall:

                    double w = 0.5 * wallThickness;
                    corners[0] -= w * (XYZ.BasisX + XYZ.BasisY);
                    corners[1] += w * (XYZ.BasisX - XYZ.BasisY);
                    corners[2] += w * (XYZ.BasisX + XYZ.BasisY);
                    corners[3] -= w * (XYZ.BasisX - XYZ.BasisY);
                    CurveArray profile = new CurveArray();
                    for (int i = 0; i < 4; ++i)
                    {
                        //Line line = createApp.NewLineBound( // 2013

                        Line line = Line.CreateBound( // 2014
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        profile.Append(line);
                    }

                    // Add a floor, a roof and the roof slope:

                    bool  structural = false;
                    Floor floor      = createDoc.NewFloor(
                        profile, structural);

                    List <Element> roofTypes
                        = new List <Element>(
                              LabUtils.GetElementsOfType(
                                  doc, typeof(RoofType),
                                  BuiltInCategory.OST_Roofs));

                    Debug.Assert(0 < roofTypes.Count,
                                 "expected at least one roof type"
                                 + " to be loaded into project");

                    // Ensure that we get a valid roof type.
                    // In Revit 2013, the first one encountered
                    // is sloped glazing with zero entries in
                    // its compound layers; actually, the entire
                    // compound structure is null:

                    //RoofType roofType = null;
                    //foreach( RoofType rt in roofTypes )
                    //{
                    //  CompoundStructure cs = rt.GetCompoundStructure();
                    //  if( null != cs
                    //    && 0 < cs.GetLayers().Count )
                    //  {
                    //    roofType = rt;
                    //    break;
                    //  }
                    //}

                    RoofType roofType = roofTypes
                                        .Cast <RoofType>()
                                        .FirstOrDefault <RoofType>(typ
                                                                   => null != typ.GetCompoundStructure());

                    ModelCurveArray modelCurves
                        = new ModelCurveArray();

                    FootPrintRoof roof
                        = createDoc.NewFootPrintRoof(profile,
                                                     levelTop, roofType, out modelCurves);

                    // Regenerate the model after roof creation,
                    // otherwise the calls to set_DefinesSlope and
                    // set_SlopeAngle throw the exception "Unable
                    // to access curves from the roof sketch."

                    doc.Regenerate();

                    // The argument to set_SlopeAngle is NOT an
                    // angle, it is really a slope, i.e. relation
                    // of height to distance, e.g. 0.5 = 6" / 12",
                    // 0.75  = 9" / 12", etc.

                    double slope = 0.3;

                    foreach (ModelCurve curve in modelCurves)
                    {
                        roof.set_DefinesSlope(curve, true);
                        roof.set_SlopeAngle(curve, slope);
                    }

                    // Add a room and a room tag:

                    Room room = createDoc.NewRoom(levelBottom, new UV(0.5 * width, 0.5 * depth));

                    //RoomTag roomTag = createDoc.NewRoomTag( room, new UV( 0.5 * width, 0.7 * depth ), null ); // 2014

                    RoomTag roomTag = createDoc.NewRoomTag(new LinkElementId(room.Id), new UV(0.5 * width, 0.7 * depth), null); // 2015

                    //doc.AutoJoinElements(); // todo: remove this, the transaction should perform this automatically

                    //LabUtils.InfoMsg( "Little house was created successfully." );

                    //#region Test setting BaseOffset and LimitOffset
                    //// 11334196 [Failed to set Room.BaseOffset and Room.LimitOffset properties]
                    //double h = 0.123;
                    //room.BaseOffset = -h;
                    //room.LimitOffset = h + h;
                    //#endregion // Test setting BaseOffset and LimitOffset

                    t.Commit();

                    return(Result.Succeeded);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Example #19
0
 public EntryMap(BuiltInParameter builtInParameter)
 {
     this.m_RevitBuiltInParameter = builtInParameter;
 }
Example #20
0
        /// <summary>
        /// Creates an entry for a given parameter.
        /// </summary>
        /// <param name="parameter">Revit parameter.</param>
        /// <returns>The PropertySetEntry.</returns>
        public static PropertySetEntry CreateParameterEntry(Parameter parameter, BuiltInParameter builtInParameter)
        {
            Definition parameterDefinition = parameter.Definition;

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

            PropertyType propertyType = PropertyType.Text;

            switch (parameter.StorageType)
            {
            case StorageType.None:
                return(null);

            case StorageType.Integer:
            {
                // YesNo or actual integer?
                if (parameterDefinition.GetDataType() == SpecTypeId.Boolean.YesNo)
                {
                    propertyType = PropertyType.Boolean;
                }
                else if (parameterDefinition.GetDataType().Empty())
                {
                    propertyType = PropertyType.Identifier;
                }
                else
                {
                    propertyType = PropertyType.Count;
                }
                break;
            }

            case StorageType.Double:
            {
                bool        assigned = true;
                ForgeTypeId type     = parameterDefinition.GetDataType();
                if (type == SpecTypeId.Angle)
                {
                    propertyType = PropertyType.PlaneAngle;
                }
                else if (type == SpecTypeId.Area ||
                         type == SpecTypeId.CrossSection ||
                         type == SpecTypeId.ReinforcementArea ||
                         type == SpecTypeId.SectionArea)
                {
                    propertyType = PropertyType.Area;
                }
                else if (type == SpecTypeId.BarDiameter ||
                         type == SpecTypeId.CrackWidth ||
                         type == SpecTypeId.Displacement ||
                         type == SpecTypeId.CableTraySize ||
                         type == SpecTypeId.ConduitSize ||
                         type == SpecTypeId.Length ||
                         type == SpecTypeId.DuctInsulationThickness ||
                         type == SpecTypeId.DuctLiningThickness ||
                         type == SpecTypeId.DuctSize ||
                         type == SpecTypeId.HvacRoughness ||
                         type == SpecTypeId.PipeInsulationThickness ||
                         type == SpecTypeId.PipeSize ||
                         type == SpecTypeId.PipingRoughness ||
                         type == SpecTypeId.ReinforcementCover ||
                         type == SpecTypeId.ReinforcementLength ||
                         type == SpecTypeId.ReinforcementSpacing ||
                         type == SpecTypeId.SectionDimension ||
                         type == SpecTypeId.SectionProperty ||
                         type == SpecTypeId.WireDiameter ||
                         type == SpecTypeId.SurfaceAreaPerUnitLength)
                {
                    propertyType = PropertyType.Length;
                }
                else if (type == SpecTypeId.ColorTemperature)
                {
                    propertyType = PropertyType.ColorTemperature;
                }
                else if (type == SpecTypeId.Currency)
                {
                    propertyType = PropertyType.Currency;
                }
                else if (type == SpecTypeId.Efficacy)
                {
                    propertyType = PropertyType.ElectricalEfficacy;
                }
                else if (type == SpecTypeId.LuminousIntensity)
                {
                    propertyType = PropertyType.LuminousIntensity;
                }
                else if (type == SpecTypeId.Illuminance)
                {
                    propertyType = PropertyType.Illuminance;
                }
                else if (type == SpecTypeId.ApparentPower ||
                         type == SpecTypeId.ElectricalPower ||
                         type == SpecTypeId.Wattage ||
                         type == SpecTypeId.HvacPower)
                {
                    propertyType = PropertyType.Power;
                }
                else if (type == SpecTypeId.Current)
                {
                    propertyType = PropertyType.ElectricCurrent;
                }
                else if (type == SpecTypeId.ElectricalPotential)
                {
                    propertyType = PropertyType.ElectricVoltage;
                }
                else if (type == SpecTypeId.ElectricalFrequency)
                {
                    propertyType = PropertyType.Frequency;
                }
                else if (type == SpecTypeId.LuminousFlux)
                {
                    propertyType = PropertyType.LuminousFlux;
                }
                else if (type == SpecTypeId.ElectricalTemperature ||
                         type == SpecTypeId.HvacTemperature ||
                         type == SpecTypeId.PipingTemperature)
                {
                    propertyType = PropertyType.ThermodynamicTemperature;
                }
                else if (type == SpecTypeId.Force)
                {
                    propertyType = PropertyType.Force;
                }
                else if (type == SpecTypeId.AirFlow ||
                         type == SpecTypeId.Flow)
                {
                    propertyType = PropertyType.VolumetricFlowRate;
                }
                else if (type == SpecTypeId.HvacPressure ||
                         type == SpecTypeId.PipingPressure ||
                         type == SpecTypeId.Stress)
                {
                    propertyType = PropertyType.Pressure;
                }
                else if (type == SpecTypeId.MassDensity)
                {
                    propertyType = PropertyType.MassDensity;
                }
                else if (type == SpecTypeId.PipingVolume ||
                         type == SpecTypeId.ReinforcementVolume ||
                         type == SpecTypeId.SectionModulus ||
                         type == SpecTypeId.Volume)
                {
                    propertyType = PropertyType.Volume;
                }
                else if (type == SpecTypeId.PipingMassPerTime)
                {
                    propertyType = PropertyType.MassFlowRate;
                }
                else if (type == SpecTypeId.AngularSpeed)
                {
                    propertyType = PropertyType.RotationalFrequency;
                }
                else
                {
                    assigned = false;
                }

                if (!assigned)
                {
                    propertyType = PropertyType.Real;
                }
                break;
            }

            case StorageType.String:
            {
                propertyType = PropertyType.Text;
                break;
            }

            case StorageType.ElementId:
            {
                propertyType = PropertyType.Label;
                break;
            }
            }

            return(new PropertySetEntry(propertyType, parameterDefinition.Name, builtInParameter));
        }
Example #21
0
        /// <summary>
        /// Gets string value from built-in parameter of an element.
        /// </summary>
        /// <param name="element">
        /// The element.
        /// </param>
        /// <param name="builtInParameter">
        /// The built-in parameter.
        /// </param>
        /// <param name="propertyValue">
        /// The output property value.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when element is null.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Thrown when builtInParameter in invalid.
        /// </exception>
        /// <returns>
        /// True if get the value successfully, false otherwise.
        /// </returns>
        public static bool GetStringValueFromElement(Element element, BuiltInParameter builtInParameter, out string propertyValue)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            if (builtInParameter == BuiltInParameter.INVALID)
                throw new ArgumentException("BuiltInParameter is INVALID", "builtInParameter");

            propertyValue = String.Empty;

            Parameter parameter = element.get_Parameter(builtInParameter);
            if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String)
            {
                propertyValue = parameter.AsString();
                return true;
            }

            return false;
        }
Example #22
0
        void ReconstructFamilyInstanceByLocation
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            [Description("Location where to place the element. Point or plane is accepted.")]
            Rhino.Geometry.Plane location,
            Autodesk.Revit.DB.FamilySymbol type,
            Optional <Autodesk.Revit.DB.Level> level,
            [Optional] Autodesk.Revit.DB.Element host
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            location = location.ChangeUnits(scaleFactor);

            if (!location.IsValid)
            {
                ThrowArgumentException(nameof(location), "Should be a valid point or plane.");
            }

            SolveOptionalLevel(ref level, doc, location.Origin.Z, nameof(level));

            if (host == null && type.Family.FamilyPlacementType == FamilyPlacementType.OneLevelBasedHosted)
            {
                ThrowArgumentNullException(nameof(host), $"This family requires a host.");
            }

            if (!type.IsActive)
            {
                type.Activate();
            }

            ChangeElementTypeId(ref element, type.Id);

            bool hasSameHost = false;

            if (element is FamilyInstance familyInstance)
            {
                hasSameHost = (familyInstance.Host?.Id ?? ElementId.InvalidElementId) == (host?.Id ?? ElementId.InvalidElementId);
                if (familyInstance.Host == null)
                {
                    if (element?.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_PARAM) is Parameter freeHostParam)
                    {
                        var freeHostName = freeHostParam.AsString();
                        hasSameHost = freeHostName.EndsWith(host?.Name ?? level.Value.Name);
                    }
                }
            }

            if
            (
                hasSameHost &&
                element is FamilyInstance &&
                element.Location is LocationPoint locationPoint
            )
            {
                using (var levelParam = element.get_Parameter(BuiltInParameter.FAMILY_LEVEL_PARAM))
                {
                    if (levelParam.AsElementId() != level.Value.Id)
                    {
                        levelParam.Set(level.Value.Id);
                        doc.Regenerate();
                    }
                }

                var newOrigin = location.Origin.ToHost();
                if (!newOrigin.IsAlmostEqualTo(locationPoint.Point))
                {
                    element.Pinned      = false;
                    locationPoint.Point = newOrigin;
                    element.Pinned      = true;
                }
            }
            else
            {
                var creationData = new List <Autodesk.Revit.Creation.FamilyInstanceCreationData>()
                {
                    new Autodesk.Revit.Creation.FamilyInstanceCreationData(location.Origin.ToHost(), type, host, level.Value, Autodesk.Revit.DB.Structure.StructuralType.NonStructural)
                };

                var newElementIds = doc.IsFamilyDocument ?
                                    doc.FamilyCreate.NewFamilyInstances2(creationData) :
                                    doc.Create.NewFamilyInstances2(creationData);

                if (newElementIds.Count != 1)
                {
                    doc.Delete(newElementIds);
                    throw new InvalidOperationException();
                }

                var parametersMask = new BuiltInParameter[]
                {
                    BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM,
                    BuiltInParameter.ELEM_FAMILY_PARAM,
                    BuiltInParameter.ELEM_TYPE_PARAM,
                    BuiltInParameter.FAMILY_LEVEL_PARAM
                };

                ReplaceElement(ref element, doc.GetElement(newElementIds.First()), parametersMask);
            }

            if (element is FamilyInstance instance && instance.Host == null)
            {
                element.Pinned = false;
                SetTransform(instance, location.Origin.ToHost(), location.XAxis.ToHost(), location.YAxis.ToHost());
                element.Pinned = true;
            }
        }
Example #23
0
 public static FilteredElementCollector WhereParameterEqualsTo(this FilteredElementCollector collector, BuiltInParameter paramId, string value, bool caseSensitive = true)
 {
     using (var provider = new ParameterValueProvider(new ElementId(paramId)))
         using (var evaluator = new FilterStringEquals())
             using (var rule = new FilterStringRule(provider, evaluator, value, caseSensitive))
                 using (var filter = new ElementParameterFilter(rule))
                     return(collector.WherePasses(filter));
 }
        protected virtual void CreateParametersInternal(Document doc, Element element)
        {
            if (element != null)
            {
                // Set the element name.
                SetName(doc, element);

                // Set the element description.
                SetDescription(doc, element);

                // The list of materials.
                SetMaterialParameter(doc, element);

                // Set the "IfcSystem" parameter.
                SetSystemParameter(doc, element);

                // Set the element GUID.
                bool             elementIsType = (element is ElementType);
                BuiltInParameter ifcGUIDId     = GetGUIDParameter(element, elementIsType);
                Parameter        guidParam     = element.get_Parameter(ifcGUIDId);
                if (guidParam != null)
                {
                    if (!guidParam.IsReadOnly)
                    {
                        guidParam.Set(GlobalId);
                    }
                }
                else
                {
                    ExporterIFCUtils.AddValueString(element, new ElementId(ifcGUIDId), GlobalId);
                }

                // Set the "IfcExportAs" parameter.
                string ifcExportAs = IFCCategoryUtil.GetCustomCategoryName(this);
                if (!string.IsNullOrWhiteSpace(ifcExportAs))
                {
                    IFCPropertySet.AddParameterString(doc, element, "IfcExportAs", ifcExportAs, Id);
                }

                // Add property set-based parameters.
                // We are going to create this "fake" parameter so that we can filter elements in schedules based on their property sets.
                string propertySetListName = elementIsType ? "Type IfcPropertySetList" : "IfcPropertySetList";
                IFCPropertySet.AddParameterString(doc, element, propertySetListName, "", Id);

                // Set the IFCElementAssembly Parameter
                if (Decomposes != null && Decomposes is IFCElementAssembly)
                {
                    IFCPropertySet.AddParameterString(doc, element, "IfcElementAssembly", Decomposes.Name, Id);
                }

                // Set additional parameters (if any), e.g. for Classification assignments
                if (AdditionalIntParameters.Count > 0)
                {
                    foreach (KeyValuePair <string, object> parItem in AdditionalIntParameters)
                    {
                        if (parItem.Value is string)
                        {
                            IFCPropertySet.AddParameterString(doc, element, parItem.Key, (string)parItem.Value, Id);
                        }
                        else if (parItem.Value is double)
                        {
                            IFCPropertySet.AddParameterDouble(doc, element, parItem.Key, UnitType.UT_Custom, (double)parItem.Value, Id);
                        }
                        else if (parItem.Value is int)
                        {
                            IFCPropertySet.AddParameterInt(doc, element, parItem.Key, (int)parItem.Value, Id);
                        }
                        else if (parItem.Value is bool)
                        {
                            IFCPropertySet.AddParameterBoolean(doc, element, parItem.Key, (bool)parItem.Value, Id);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets string value from built-in parameter of an element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built-in parameter.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when element is null.</exception>
        /// <exception cref="System.ArgumentException">Thrown when builtInParameter in invalid.</exception>
        /// <returns>The parameter, or null if not found.</returns>
        public static Parameter GetStringValueFromElement(Element element, BuiltInParameter builtInParameter, out string propertyValue)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            if (builtInParameter == BuiltInParameter.INVALID)
                throw new ArgumentException("BuiltInParameter is INVALID", "builtInParameter");

            propertyValue = String.Empty;

            Parameter parameter = element.get_Parameter(builtInParameter);
            if (parameter != null && parameter.HasValue)
            {
                switch (parameter.StorageType)
                {
                    case StorageType.Double:
                        propertyValue = parameter.AsDouble().ToString();
                        return parameter;
                    case StorageType.Integer:
                        propertyValue = parameter.AsInteger().ToString();
                        return parameter;
                    case StorageType.String:
                        propertyValue = parameter.AsString();
                        return parameter;
                    case StorageType.ElementId:
                        propertyValue = PropertyUtil.ElementIdParameterAsString(parameter);
                        return parameter;
                }
            }

            return null;
        }
Example #26
0
        /// <summary>
        /// get the room property and Department property according the property name
        /// </summary>
        /// <param name="room">a instance of room class</param>
        /// <param name="paraEnum">the property name</param>
        public String GetProperty(Room room, BuiltInParameter paraEnum)
        {
            String propertyValue = null;  //the value of parameter

            // get the parameter via the parameterId
            Parameter param = room.get_Parameter(paraEnum);
            if (null == param)
            {
                return "";
            }
            // get the parameter's storage type
            StorageType storageType = param.StorageType;
            switch (storageType)
            {
                case StorageType.Integer:
                    int iVal = param.AsInteger();
                    propertyValue = iVal.ToString();
                    break;
                case StorageType.String:
                    String stringVal = param.AsString();
                    propertyValue = stringVal;
                    break;
                case StorageType.Double:
                    Double dVal = param.AsDouble();
                    dVal = Math.Round(dVal, 2);
                    propertyValue = dVal.ToString();
                    break;
                default:
                    break;
            }
            return propertyValue;
        }
        /// <summary>
        /// Gets element id value from parameter of an element or its element type.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built in parameter.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <returns>The parameter, or null if not found.</returns>
        public static Parameter GetElementIdValueFromElementOrSymbol(Element element, BuiltInParameter builtInParameter, out ElementId propertyValue)
        {
            Parameter parameter = GetElementIdValueFromElement(element, builtInParameter, out propertyValue);
            if (parameter != null)
                return parameter;

            Document document = element.Document;
            ElementId typeId = element.GetTypeId();

            Element elemType = document.GetElement(typeId);
            if (elemType != null)
                return GetElementIdValueFromElement(elemType, builtInParameter, out propertyValue);
            
            return null;
        }
 public QuantityEntry(string propertyName, BuiltInParameter builtInParameter)
     : base(propertyName, new QuantityEntryMap(propertyName) { RevitBuiltInParameter = builtInParameter })
 {
 }
Example #29
0
        /// <summary>
        /// Get the room property value according the parameter name
        /// </summary>
        /// <param name="activeDoc">Current active document.</param>
        /// <param name="room">an instance of room class</param>
        /// <param name="paraEnum">the parameter used to get parameter value</param>
        /// <param name="useValue">convert parameter to value type or not.
        /// if true, the value of parameter will be with unit.
        /// if false, the value of parameter will be without unit.</param>
        /// <returns>the string value of property specified by shared parameter</returns>
        public static String GetProperty(Document activeDoc, Room room, BuiltInParameter paraEnum, bool useValue)
        {
            String propertyValue = null;  //the value of parameter

            // Assuming the build in parameter is legal for room.
            // if the room is not placed, some properties are not available, i.g. Level name, Area ...
            // trying to retrieve them will throw exception;
            // however some parameters are available, e.g.: name, number
            Parameter param;
            try
            {
                param = room.get_Parameter(paraEnum);
            }
            catch (Exception)
            {
                // throwing exception for this parameter is acceptable if it's a unplaced room
                if (null == room.Location)
                {
                    propertyValue = "Not Placed";
                    return propertyValue;
                }
                else
                {
                    throw new Exception("Illegal built in parameter.");
                }
            }

            // get the parameter via the built in parameter
            if (null == param)
            {
                return "";
            }

            // get the parameter's storage type and convert parameter to string
            StorageType storageType = param.StorageType;
            switch (storageType)
            {
                case StorageType.Integer:
                    int iVal = param.AsInteger();
                    propertyValue = iVal.ToString();
                    break;
                case StorageType.String:
                    propertyValue = param.AsString();
                    break;
                case StorageType.Double:
                    // AsValueString will make the return string with unit, it's appreciated.
                    if (useValue)
                    {
                        propertyValue = param.AsValueString();
                    }
                    else
                    {
                        propertyValue = param.AsDouble().ToString();
                    }
                    break;
                case StorageType.ElementId:
                    Autodesk.Revit.DB.ElementId elemId = param.AsElementId();
                    Element elem = activeDoc.get_Element(elemId);
                    propertyValue = elem.Name;
                    break;
                default:
                    propertyValue = param.AsString();
                    break;
            }

            return propertyValue;
        }
Example #30
0
 /// <summary>
 /// set parameter whose storage type is double
 /// </summary>
 /// <param name="elem">Element has parameter</param>
 /// <param name="builtInPara">BuiltInParameter to find parameter</param>
 /// <param name="value">value to set</param>
 /// <returns>is successful</returns>
 private bool SetParameter(ModelElement elem, 
     BuiltInParameter builtInPara, double value)
 {
     Parameter para = elem.get_Parameter(builtInPara);
     if (null != para && para.StorageType == StorageType.Double && !para.IsReadOnly)
     {
        var result = para.Set(value);
        return result;
     }
     return false;
 }
        public Result ExecuteObsolete(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            BindingMap bindings = doc.ParameterBindings;
            //Dictionary<string, Guid> guids = new Dictionary<string, Guid>();
            Dictionary <Definition, object> mapDefToGuid = new Dictionary <Definition, object>();

            int n = bindings.Size;

            Debug.Print("{0} shared parementer{1} defined{2}",
                        n, Util.PluralSuffix(n), Util.DotOrColon(n));

            if (0 < n)
            {
                DefinitionBindingMapIterator it
                    = bindings.ForwardIterator();

                while (it.MoveNext())
                {
                    Definition d = it.Key as Definition;
                    Binding    b = it.Current as Binding;
                    if (d is ExternalDefinition)
                    {
                        Guid g = ((ExternalDefinition)d).GUID;
                        Debug.Print(d.Name + ": " + g.ToString());
                        mapDefToGuid.Add(d, g);
                    }
                    else
                    {
                        Debug.Assert(d is InternalDefinition);

                        // this built-in parameter is INVALID:

                        BuiltInParameter bip = ((InternalDefinition)d).BuiltInParameter;
                        Debug.Print(d.Name + ": " + bip.ToString());

                        // if have a definition file and group name, we can still determine the GUID:

                        //Guid g = SharedParamGuid( app, "Identity data", d.Name );

                        mapDefToGuid.Add(d, null);
                    }
                }
            }

            List <Element> walls = new List <Element>();

            if (!Util.GetSelectedElementsOrAll(
                    walls, uidoc, typeof(Wall)))
            {
                Selection sel = uidoc.Selection;
                message = (0 < sel.GetElementIds().Count)
        ? "Please select some wall elements."
        : "No wall elements found.";
            }
            else
            {
                //List<string> keys = new List<string>( mapDefToGuid.Keys );
                //keys.Sort();

                foreach (Wall wall in walls)
                {
                    Debug.Print(Util.ElementDescription(wall));

                    foreach (Definition d in mapDefToGuid.Keys)
                    {
                        object o = mapDefToGuid[d];

                        Parameter p = (null == o)
            ? wall.get_Parameter(d)
            : wall.get_Parameter((Guid)o);

                        string s = (null == p)
            ? "<null>"
            : p.AsValueString();

                        Debug.Print(d.Name + ": " + s);
                    }
                }
            }
            return(Result.Failed);
        }
Example #32
0
 /// <summary>
 /// Create FilterRuleBuilder for double FilterRule
 /// </summary>
 /// <param name="param">Parameter of FilterRule.</param>
 /// <param name="ruleCriteria">Rule criteria.</param>
 /// <param name="ruleValue">Rule value.</param>
 /// <param name="tolerance">Epsilon for double values comparison.</param>
 public FilterRuleBuilder(BuiltInParameter param, String ruleCriteria, double ruleValue, double tolearance)
 {
     InitializeMemebers();
     //
     // set data with specified values
     ParamType = StorageType.Double;
     Parameter = param;
     RuleCriteria = ruleCriteria;
     RuleValue = ruleValue.ToString();
     Epsilon = tolearance;
 }
Example #33
0
        static public Result Execute2(
            ExternalCommandData commandData,
            ref String message,
            ElementSet elements,
            bool populateFullHierarchy)
        {
            try
            {
                WaitCursor    waitCursor = new WaitCursor();
                UIApplication app        = commandData.Application;
                Document      doc        = app.ActiveUIDocument.Document;
                //
                // display electrical equipment instance data,
                // i.e. equipment_name:system_name, and convert it to
                // a map from key = panel:circuit --> equipment:
                //
                List <Element> equipment = Util.GetElectricalEquipment(doc);
                int            n         = equipment.Count;
                Debug.WriteLine(string.Format("Retrieved {0} electrical equipment instance{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                Dictionary <string, List <Element> > mapPanelAndSystemToEquipment = new Dictionary <string, List <Element> >();
                foreach (FamilyInstance elecEqip in equipment)
                {
                    ListEquipment(elecEqip, mapPanelAndSystemToEquipment);
                }
                //
                // determine mapping from panel to circuit == electrical system:
                //
                Dictionary <string, ElectricalSystemSet> mapPanelToSystems = new Dictionary <string, ElectricalSystemSet>();
                IList <Element> systems = Util.GetElectricalSystems(doc);
                n = systems.Count;
                Debug.WriteLine(string.Format("Retrieved {0} electrical system{1}.", n, Util.PluralSuffix(n)));
                //
                // all circuits which are fed from the same family instance have
                // the same panel name, so you can retrieve all of these circuits.
                //
                // todo: there is an issue here if there are several different panels
                // with the same name! they will get merged in the tree view,
                // but they should stay separate. possible workaround: add the
                // element id to keep them separate, and then remove it again
                // when displaying in tree view.
                //
                foreach (ElectricalSystem system in systems)
                {
                    string panelName = system.PanelName;

                    Debug.WriteLine("  system " + system.Name + ": panel " + panelName
                                    + " load classifications " + system.LoadClassifications);

                    if (!mapPanelToSystems.ContainsKey(panelName))
                    {
                        mapPanelToSystems.Add(panelName, new ElectricalSystemSet());
                    }
                    mapPanelToSystems[panelName].Insert(system);
                }
                n = mapPanelToSystems.Count;
                //Debug.WriteLine( string.Format( "Mapping from the {0} panel{1} to systems, system name :circuit name(connectors/unused connectors):", n, Util.PluralSuffix( n ) ) );
                Debug.WriteLine(string.Format("Mapping from the {0} panel{1} to electrical systems == circuits:",
                                              n, Util.PluralSuffix(n)));
                List <string> keys = new List <string>(mapPanelToSystems.Keys);
                keys.Sort();
                string s;
                foreach (string panelName in keys)
                {
                    s = string.Empty;
                    foreach (ElectricalSystem system in mapPanelToSystems[panelName])
                    {
                        ConnectorManager cmgr = system.ConnectorManager;

                        // the connector manager does not include any logical connectors
                        // in the Revit 2009 fcs and wu1 API, only physical ones:
                        //Debug.Assert( 0 == cmgr.Connectors.Size,
                        //  "electrical connector count is always zero" );

                        Debug.Assert(cmgr.UnusedConnectors.Size <= cmgr.Connectors.Size,
                                     "unused connectors is a subset of connectors");

                        Debug.Assert(system.Name.Equals(system.CircuitNumber),
                                     "ElectricalSystem Name and CircuitNumber properties are always identical");

                        //s += ( 0 < s.Length ? ", " : ": " ) + system.Name;

                        s += (0 < s.Length ? ", " : ": ") + system.Name // + ":" + system.CircuitNumber
                             + "(" + cmgr.Connectors.Size.ToString()
                             + "/" + cmgr.UnusedConnectors.Size.ToString() + ")";
                    }
                    Debug.WriteLine("  " + panelName + s);
                }

                /*
                 * Debug.WriteLine( "Mapping from panels to systems to connected elements:" );
                 * foreach( string panelName in keys )
                 * {
                 * Debug.WriteLine( "  panel " + panelName + ":" );
                 * foreach( ElectricalSystem system in mapPanelToSystems[panelName] )
                 * {
                 *  ConnectorManager cmgr = system.ConnectorManager;
                 *  n = cmgr.Connectors.Size;
                 *  Debug.WriteLine( string.Format( "    system {0} has {1} connector{2}{3}", system.Name, n, Util.PluralSuffix( n ), Util.DotOrColon( n ) ) );
                 *  foreach( Connector connector in system.ConnectorManager.Connectors )
                 *  {
                 *    Element owner = connector.Owner;
                 *    Debug.WriteLine( string.Format( "    owner {0} {1}, domain {2}", owner.Name, owner.Id.IntegerValue, connector.Domain ) );
                 *  }
                 * }
                 * }
                 */

                //
                // list all circuit elements:
                //
                // this captures all elements in circuits H-2: 2, 4, 6 etc,
                // but not the element T2 in H-2:1,3,5, because it has no circuit number,
                // just a panel number.
                //
                BuiltInParameter bipPanel        = BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM;
                BuiltInParameter bipCircuit      = BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER;
                IList <Element>  circuitElements = Util.GetCircuitElements(doc);
                n = circuitElements.Count;
                Debug.WriteLine(string.Format("Retrieved {0} circuit element{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                Dictionary <string, List <Element> > mapPanelAndCircuitToElements = new Dictionary <string, List <Element> >();
                foreach (Element e in circuitElements)
                {
                    string circuitName = e.get_Parameter(bipCircuit).AsString();
                    //
                    // do not map an electrical system to itself:
                    //
                    if (!(e is ElectricalSystem && e.Name.Equals(circuitName)))
                    {
                        string panelName = e.get_Parameter(bipPanel).AsString();
                        string key       = panelName + ":" + circuitName;
                        Debug.WriteLine(string.Format("  {0} <{1} {2}> panel:circuit {3}", e.GetType().Name, e.Name, e.Id.IntegerValue, key));
                        if (!mapPanelAndCircuitToElements.ContainsKey(key))
                        {
                            mapPanelAndCircuitToElements.Add(key, new List <Element>());
                        }
                        mapPanelAndCircuitToElements[key].Add(e);
                    }
                }
                n = mapPanelAndCircuitToElements.Count;
                Debug.WriteLine(string.Format("Mapped circuit elements to {0} panel:circuit{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                keys.Clear();
                keys.AddRange(mapPanelAndCircuitToElements.Keys);
                keys.Sort(new PanelCircuitComparer());
                foreach (string panelAndCircuit in keys)
                {
                    List <string> a = new List <string>(mapPanelAndCircuitToElements[panelAndCircuit].Count);
                    foreach (Element e in mapPanelAndCircuitToElements[panelAndCircuit])
                    {
                        FamilyInstance inst = e as FamilyInstance;
                        a.Add((null == inst ? e.Category.Name : inst.Symbol.Family.Name) + " " + e.Name);
                    }
                    a.Sort();
                    s = string.Join(", ", a.ToArray());
                    Debug.WriteLine("  " + panelAndCircuit + ": " + s);
                }

                #region Aborted attempt to use RBS_ELEC_CIRCUIT_PANEL_PARAM
#if USE_RBS_ELEC_CIRCUIT_PANEL_PARAM
                //
                // list all panel elements:
                //
                // selecting all elements with a BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER
                // captures all elements in circuits H-2: 2, 4, 6 etc, but not the element
                // T2 in H-2:1,3,5, because it has no circuit number, just a panel number.
                //
                // so grab everything with a panel number instead.
                //
                // all this added to the selection was lots of wires, so forget it again.
                //
                BuiltInParameter bipCircuit      = BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER;
                BuiltInParameter bipPanel        = BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM;
                List <Element>   circuitElements = new List <Element>();
                Util.GetElementsWithParameter(circuitElements, bipPanel, app);
                n = circuitElements.Count;
                Debug.WriteLine(string.Format("Retrieved {0} circuit element{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                Dictionary <string, List <Element> > mapCircuitToElements = new Dictionary <string, List <Element> >();
                foreach (Element e in circuitElements)
                {
                    string    panelName = e.get_Parameter(bipPanel).AsString();
                    Parameter p         = e.get_Parameter(bipCircuit);
                    if (null == p)
                    {
                        Debug.WriteLine(string.Format("  {0} <{1} {2}> panel:circuit {3}:null", e.GetType().Name, e.Name, e.Id.IntegerValue, panelName));
                    }
                    else
                    {
                        string circuitName = p.AsString();
                        //
                        // do not map an electrical system to itself:
                        //
                        if (!(e is ElectricalSystem && e.Name.Equals(circuitName)))
                        {
                            string key = panelName + ":" + circuitName;
                            Debug.WriteLine(string.Format("  {0} <{1} {2}> panel:circuit {3}", e.GetType().Name, e.Name, e.Id.IntegerValue, key));
                            if (!mapCircuitToElements.ContainsKey(key))
                            {
                                mapCircuitToElements.Add(key, new List <Element>());
                            }
                            mapCircuitToElements[key].Add(e);
                        }
                    }
                }
                n = mapCircuitToElements.Count;
                Debug.WriteLine(string.Format("Mapped circuit elements to {0} panel:circuit{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                keys.Clear();
                keys.AddRange(mapCircuitToElements.Keys);
                keys.Sort(new PanelCircuitComparer());
                foreach (string circuitName in keys)
                {
                    List <string> a = new List <string>(mapCircuitToElements[circuitName].Count);
                    foreach (Element e in mapCircuitToElements[circuitName])
                    {
                        FamilyInstance inst = e as FamilyInstance;
                        a.Add((null == inst ? e.Category.Name : inst.Symbol.Family.Name) + " " + e.Name);
                    }
                    a.Sort();
                    s = string.Join(", ", a.ToArray());
                    Debug.WriteLine("  " + circuitName + ": " + s);
                }
#endif // USE_RBS_ELEC_CIRCUIT_PANEL_PARAM
                #endregion // Aborted attempt to use RBS_ELEC_CIRCUIT_PANEL_PARAM

                //
                // merge the two trees of equipment and circuit elements
                // to reproduce the content of the system browser ... the
                // hardest part of this is setting up the PanelSystemComparer
                // to generate the same sort order as the system browser:
                //
                //n = mapPanelAndSystemToEquipment.Count + mapPanelAndCircuitToElements.Count;
                //Dictionary<string, List<Element>> mapSystemBrowser = new Dictionary<string, List<Element>>( n );
                Dictionary <string, List <Element> > mapSystemBrowser = new Dictionary <string, List <Element> >(mapPanelAndCircuitToElements);
                foreach (KeyValuePair <string, List <Element> > pair in mapPanelAndSystemToEquipment)
                {
                    mapSystemBrowser[pair.Key] = pair.Value;
                }
                n = mapSystemBrowser.Count;
                Debug.WriteLine(string.Format("Mapped equipment + circuit elements to {0} panel:system{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                keys.Clear();
                keys.AddRange(mapSystemBrowser.Keys);
                keys.Sort(new PanelSystemComparer());
                foreach (string panelAndSystem in keys)
                {
                    List <string> a = new List <string>(mapSystemBrowser[panelAndSystem].Count);
                    foreach (Element e in mapSystemBrowser[panelAndSystem])
                    {
                        a.Add(Util.BrowserDescription(e));
                    }
                    a.Sort();
                    s = string.Join(", ", a.ToArray());
                    Debug.WriteLine(string.Format("  {0}({1}): ", panelAndSystem, a.Count) + s);
                }
                //
                // get the electrical equipment category id:
                //
                Categories categories = doc.Settings.Categories;
                ElementId  electricalEquipmentCategoryId = categories.get_Item(BuiltInCategory.OST_ElectricalEquipment).Id;
                //
                // we have assembled the required information and structured it
                // sufficiently for the tree view, so now let us go ahead and display it:
                //
                CmdInspectElectricalForm dialog = new CmdInspectElectricalForm(mapSystemBrowser, electricalEquipmentCategoryId, populateFullHierarchy);
                dialog.Show();
                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
        ///
        /// Return a string value for the specified
        /// built-in parameter if it is available on
        /// the given element, else an empty string.
        ///
        string GetParameterValueString(
            Element e,
            BuiltInParameter bip)
        {
            Parameter p = e.get_Parameter( bip );

              string s = string.Empty;

              if( null != p )
              {
            switch( p.StorageType )
            {
              case StorageType.Integer:
            s = p.AsInteger().ToString();
            break;

              case StorageType.ElementId:
            s = p.AsElementId().IntegerValue.ToString();
            break;

              case StorageType.Double:
            s = Util.RealString( p.AsDouble() );
            break;

              case StorageType.String:
            s = string.Format( "{0} ({1})",
              p.AsValueString(),
              Util.RealString( p.AsDouble() ) );
            break;

              default: s = "";
            break;
            }
            s = ", " + bip.ToString() + "=" + s;
              }
              return s;
        }
Example #35
0
        void ReconstructGridByCurve
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Curve curve,
            Optional <Autodesk.Revit.DB.GridType> type
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            if (scaleFactor != 1.0)
            {
                curve.Scale(scaleFactor);
            }

            SolveOptionalType(ref type, doc, ElementTypeGroup.GridType, nameof(type));

            if (curve.TryGetLine(out var line, Revit.VertexTolerance))
            {
                ReplaceElement(ref element, Grid.Create(doc, line.ToHost()));
                ChangeElementTypeId(ref element, type.Value.Id);
            }
            else if (curve.TryGetArc(out var arc, Revit.VertexTolerance))
            {
                ReplaceElement(ref element, Grid.Create(doc, arc.ToHost()));
                ChangeElementTypeId(ref element, type.Value.Id);
            }
            else
            {
                using (var curveLoop = new CurveLoop())
                    using (var polyline = curve.ToArcsAndLines(Revit.VertexTolerance, Revit.AngleTolerance, Revit.ShortCurveTolerance, double.PositiveInfinity))
                    {
                        int count = polyline.SegmentCount;
                        for (int s = 0; s < count; ++s)
                        {
                            var segment = polyline.SegmentCurve(s);

                            if (segment is Rhino.Geometry.LineCurve l)
                            {
                                curveLoop.Append(l.ToHost());
                            }
                            else if (segment is Rhino.Geometry.ArcCurve a)
                            {
                                curveLoop.Append(a.ToHost());
                            }
                            else
                            {
                                ThrowArgumentException(nameof(curve), "Invalid curve type.");
                            }
                        }

                        curve.TryGetPlane(out var plane);
                        var sketchPlane = SketchPlane.Create(doc, plane.ToHost());

                        var parametersMask = new BuiltInParameter[]
                        {
                            BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM,
                            BuiltInParameter.ELEM_FAMILY_PARAM,
                            BuiltInParameter.ELEM_TYPE_PARAM
                        };

                        ReplaceElement(ref element, doc.GetElement(MultiSegmentGrid.Create(doc, type.Value.Id, curveLoop, sketchPlane.Id)), parametersMask);
                    }
            }
        }
Example #36
0
 public EntryMap(string revitParameterName, BuiltInParameter builtInParameter)
 {
     this.m_RevitParameterName    = revitParameterName;
     this.m_RevitBuiltInParameter = builtInParameter;
 }
Example #37
0
 /// <summary>
 /// Create FilterRuleBuilder for String FilterRule
 /// </summary>
 /// <param name="param">Parameter of FilterRule.</param>
 /// <param name="ruleCriteria">Rule criteria.</param>
 /// <param name="ruleValue">Rule value.</param>
 /// <param name="caseSensitive">Indicates if rule value is case sensitive.</param>
 public FilterRuleBuilder(BuiltInParameter param, String ruleCriteria, String ruleValue, bool caseSensitive)
 {
     InitializeMemebers();
     //
     // set data with specified values
     ParamType = StorageType.String;
     Parameter = param;
     RuleCriteria = ruleCriteria;
     RuleValue = ruleValue;
     CaseSensitive = caseSensitive;
 }
Example #38
0
        /// <summary>
        /// Create a Frequency measure property from the element's parameter.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="elem">The Element.</param>
        /// <param name="revitParameterName">The name of the parameter.</param>
        /// <param name="revitBuiltInParam">The built in parameter to use, if revitParameterName isn't found.</param>
        /// <param name="ifcPropertyName">The name of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created property handle.</returns>
        public static IFCAnyHandle CreateFrequencyPropertyFromElement(IFCFile file, ExporterIFC exporterIFC, Element elem,
                                                                      string revitParameterName, BuiltInParameter revitBuiltInParam, string ifcPropertyName, PropertyValueType valueType)
        {
            IFCAnyHandle propHnd = CreateFrequencyPropertyFromElement(file, exporterIFC, elem, revitParameterName, ifcPropertyName, valueType);

            if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
            {
                return(propHnd);
            }

            if (revitBuiltInParam != BuiltInParameter.INVALID)
            {
                string builtInParamName = LabelUtils.GetLabelFor(revitBuiltInParam);
                propHnd = CreateFrequencyPropertyFromElement(file, exporterIFC, elem, builtInParamName, ifcPropertyName, valueType);
                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
                {
                    return(propHnd);
                }
            }

            return(null);
        }
Example #39
0
 /// <summary>
 /// Create FilterRuleBuilder for ElementId FilterRule
 /// </summary>
 /// <param name="param">Parameter of FilterRule.</param>
 /// <param name="ruleCriteria">Rule criteria.</param>
 /// <param name="ruleValue">Rule value.</param>
 public FilterRuleBuilder(BuiltInParameter param, String ruleCriteria, ElementId ruleValue)
 {
     InitializeMemebers();
     //
     // set data with specified values
     ParamType = StorageType.ElementId;
     Parameter = param;
     RuleCriteria = ruleCriteria;
     RuleValue = ruleValue.ToString();
 }
Example #40
0
 public PropertySetEntry(PropertyType propertyType, string propertyName, BuiltInParameter builtInParameter, PropertyCalculator propertyCalculator)
     : base(propertyName, new PropertySetEntryMap(propertyName) { RevitBuiltInParameter = builtInParameter, PropertyCalculator = propertyCalculator })
 {
     m_PropertyType = propertyType;
 }
Example #41
0
        /// <summary>
        /// Gets element id value from parameter of an element or its element type.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built in parameter.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <returns>True if get the value successfully, false otherwise.</returns>
        public static bool GetElementIdValueFromElementOrSymbol(Element element, BuiltInParameter builtInParameter, out ElementId propertyValue)
        {
            if (GetElementIdValueFromElement(element, builtInParameter, out propertyValue))
                return true;
            else
            {
                Document document = element.Document;
                ElementId typeId = element.GetTypeId();

                Element elemType = document.GetElement(typeId);
                if (elemType != null)
                {
                    return GetElementIdValueFromElement(elemType, builtInParameter, out propertyValue);
                }
                else
                    return false;
            }
        }
Example #42
0
        /// <summary>
        /// Creates an entry for a given parameter.
        /// </summary>
        /// <param name="parameter">Revit parameter.</param>
        /// <returns>The PropertySetEntry.</returns>
        public static PropertySetEntry CreateParameterEntry(Parameter parameter, BuiltInParameter builtInParameter)
        {
            Definition parameterDefinition = parameter.Definition;

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

            PropertyType propertyType = PropertyType.Text;

            switch (parameter.StorageType)
            {
            case StorageType.None:
                return(null);

            case StorageType.Integer:
            {
                // YesNo or actual integer?
                if (parameterDefinition.ParameterType == ParameterType.YesNo)
                {
                    propertyType = PropertyType.Boolean;
                }
                else if (parameterDefinition.ParameterType == ParameterType.Invalid)
                {
                    propertyType = PropertyType.Identifier;
                }
                else
                {
                    propertyType = PropertyType.Count;
                }
                break;
            }

            case StorageType.Double:
            {
                bool assigned = true;
                switch (parameterDefinition.ParameterType)
                {
                case ParameterType.Angle:
                    propertyType = PropertyType.PlaneAngle;
                    break;

                case ParameterType.Area:
                case ParameterType.HVACCrossSection:
                case ParameterType.ReinforcementArea:
                case ParameterType.SectionArea:
                case ParameterType.SurfaceArea:
                    propertyType = PropertyType.Area;
                    break;

                case ParameterType.BarDiameter:
                case ParameterType.CrackWidth:
                case ParameterType.DisplacementDeflection:
                case ParameterType.ElectricalCableTraySize:
                case ParameterType.ElectricalConduitSize:
                case ParameterType.Length:
                case ParameterType.HVACDuctInsulationThickness:
                case ParameterType.HVACDuctLiningThickness:
                case ParameterType.HVACDuctSize:
                case ParameterType.HVACRoughness:
                case ParameterType.PipeInsulationThickness:
                case ParameterType.PipeSize:
                case ParameterType.PipingRoughness:
                case ParameterType.ReinforcementCover:
                case ParameterType.ReinforcementLength:
                case ParameterType.ReinforcementSpacing:
                case ParameterType.SectionDimension:
                case ParameterType.SectionProperty:
                case ParameterType.WireSize:
                    propertyType = PropertyType.Length;
                    break;

                case ParameterType.ColorTemperature:
                    propertyType = PropertyType.ColorTemperature;
                    break;

                case ParameterType.Currency:
                    propertyType = PropertyType.Currency;
                    break;

                case ParameterType.ElectricalEfficacy:
                    propertyType = PropertyType.ElectricalEfficacy;
                    break;

                case ParameterType.ElectricalLuminousIntensity:
                    propertyType = PropertyType.LuminousIntensity;
                    break;

                case ParameterType.ElectricalIlluminance:
                    propertyType = PropertyType.Illuminance;
                    break;

                case ParameterType.ElectricalApparentPower:
                case ParameterType.ElectricalPower:
                case ParameterType.ElectricalWattage:
                case ParameterType.HVACPower:
                    propertyType = PropertyType.Power;
                    break;

                case ParameterType.ElectricalCurrent:
                    propertyType = PropertyType.ElectricCurrent;
                    break;

                case ParameterType.ElectricalPotential:
                    propertyType = PropertyType.ElectricVoltage;
                    break;

                case ParameterType.ElectricalFrequency:
                    propertyType = PropertyType.Frequency;
                    break;

                case ParameterType.ElectricalLuminousFlux:
                    propertyType = PropertyType.LuminousFlux;
                    break;

                case ParameterType.ElectricalTemperature:
                case ParameterType.HVACTemperature:
                case ParameterType.PipingTemperature:
                    propertyType = PropertyType.ThermodynamicTemperature;
                    break;

                case ParameterType.Force:
                    propertyType = PropertyType.Force;
                    break;

                case ParameterType.HVACAirflow:
                case ParameterType.PipingFlow:
                    propertyType = PropertyType.VolumetricFlowRate;
                    break;

                case ParameterType.HVACPressure:
                case ParameterType.PipingPressure:
                case ParameterType.Stress:
                    propertyType = PropertyType.Pressure;
                    break;

                case ParameterType.MassDensity:
                    propertyType = PropertyType.MassDensity;
                    break;

                case ParameterType.PipingVolume:
                case ParameterType.ReinforcementVolume:
                case ParameterType.SectionModulus:
                case ParameterType.Volume:
                    propertyType = PropertyType.Volume;
                    break;

                default:
                    assigned = false;
                    break;
                }

                if (!assigned)
                {
                    propertyType = PropertyType.Real;
                }
                break;
            }

            case StorageType.String:
            {
                propertyType = PropertyType.Text;
                break;
            }

            case StorageType.ElementId:
            {
                propertyType = PropertyType.Label;
                break;
            }
            }
            return(new PropertySetEntry(propertyType, parameterDefinition.Name, builtInParameter));
        }
Example #43
0
        /// <summary>Gets string value from built-in parameter of an element or its type.</summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built-in parameter.</param>
        /// <param name="nullAllowed">true if we allow the property value to be empty.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <returns>True if get the value successfully, false otherwise.</returns>
        public static bool GetStringValueFromElementOrSymbol(Element element, BuiltInParameter builtInParameter, bool nullAllowed, out string propertyValue)
        {
            if (GetStringValueFromElement(element, builtInParameter, out propertyValue))
            {
                if (!String.IsNullOrEmpty(propertyValue))
                    return true;
            }

            bool found = false;
            Element elementType = element.Document.GetElement(element.GetTypeId());
            if (elementType != null)
            {
                found = GetStringValueFromElement(elementType, builtInParameter, out propertyValue);
                if (found && !nullAllowed && String.IsNullOrEmpty(propertyValue))
                    found = false;
            }

            return found;
        }
Example #44
0
        /// <summary>
        /// Create a view schedule of wall category and add schedule field, filter and sorting/grouping field to it.
        /// </summary>
        /// <param name="uiDocument">UIdocument of revit file.</param>
        /// <returns>ICollection of created view schedule(s).</returns>
        private ICollection <ViewSchedule> CreateSchedules(UIDocument uiDocument)
        {
            Document document = uiDocument.Document;

            Transaction t = new Transaction(document, "Create Schedules");

            t.Start();

            List <ViewSchedule> schedules = new List <ViewSchedule>();

            //Create an empty view schedule of wall category.
            ViewSchedule schedule = ViewSchedule.CreateSchedule(document, new ElementId(BuiltInCategory.OST_Walls), ElementId.InvalidElementId);

            schedule.Name = "Wall Schedule 1";
            schedules.Add(schedule);

            //Iterate all the schedulable field gotten from the walls view schedule.
            foreach (SchedulableField schedulableField in schedule.Definition.GetSchedulableFields())
            {
                //Judge if the FieldType is ScheduleFieldType.Instance.
                if (schedulableField.FieldType == ScheduleFieldType.Instance)
                {
                    //Get ParameterId of SchedulableField.
                    ElementId parameterId = schedulableField.ParameterId;

                    //If the ParameterId is id of BuiltInParameter.ALL_MODEL_MARK then ignore next operation.
                    if (ShouldSkip(parameterId))
                    {
                        continue;
                    }

                    //Add a new schedule field to the view schedule by using the SchedulableField as argument of AddField method of Autodesk.Revit.DB.ScheduleDefinition class.
                    ScheduleField field = schedule.Definition.AddField(schedulableField);

                    //Judge if the parameterId is a BuiltInParameter.
                    if (Enum.IsDefined(typeof(BuiltInParameter), parameterId.IntegerValue))
                    {
                        BuiltInParameter bip = (BuiltInParameter)parameterId.IntegerValue;
                        //Get the StorageType of BuiltInParameter.
                        StorageType st = document.get_TypeOfStorage(bip);
                        //if StorageType is String or ElementId, set GridColumnWidth of schedule field to three times of current GridColumnWidth.
                        //And set HorizontalAlignment property to left.
                        if (st == StorageType.String || st == StorageType.ElementId)
                        {
                            field.GridColumnWidth     = 3 * field.GridColumnWidth;
                            field.HorizontalAlignment = ScheduleHorizontalAlignment.Left;
                        }
                        //For other StorageTypes, set HorizontalAlignment property to center.
                        else
                        {
                            field.HorizontalAlignment = ScheduleHorizontalAlignment.Center;
                        }
                    }


                    //Filter the view schedule by volume
                    if (field.ParameterId == new ElementId(BuiltInParameter.HOST_VOLUME_COMPUTED))
                    {
                        double         volumeFilterInCubicFt = 0.8 * Math.Pow(3.2808399, 3.0);
                        ScheduleFilter filter = new ScheduleFilter(field.FieldId, ScheduleFilterType.GreaterThan, volumeFilterInCubicFt);
                        schedule.Definition.AddFilter(filter);
                    }

                    //Group and sort the view schedule by type
                    if (field.ParameterId == new ElementId(BuiltInParameter.ELEM_TYPE_PARAM))
                    {
                        ScheduleSortGroupField sortGroupField = new ScheduleSortGroupField(field.FieldId);
                        sortGroupField.ShowHeader = true;
                        schedule.Definition.AddSortGroupField(sortGroupField);
                    }
                }
            }

            t.Commit();

            uiDocument.ActiveView = schedule;

            return(schedules);
        }
        // This function is static to make sure that no properties are used directly from the entry.
        private static IFCAnyHandle CreatePropertyFromElementOrSymbolBase(IFCFile file, ExporterIFC exporterIFC, Element element,
            string revitParamNameToUse, string ifcPropertyName, BuiltInParameter builtInParameter,
            PropertyType propertyType, PropertyValueType valueType, Type propertyEnumerationType)
        {
            IFCAnyHandle propHnd = null;

            switch (propertyType)
            {
                case PropertyType.Text:
                    {
                        propHnd = PropertyUtil.CreateTextPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                        break;
                    }
                case PropertyType.Label:
                    {
                        propHnd = PropertyUtil.CreateLabelPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                        break;
                    }
                case PropertyType.Identifier:
                    {
                        propHnd = PropertyUtil.CreateIdentifierPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Boolean:
                    {
                        propHnd = PropertyUtil.CreateBooleanPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Logical:
                    {
                        propHnd = PropertyUtil.CreateLogicalPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Integer:
                    {
                        propHnd = PropertyUtil.CreateIntegerPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Real:
                    {
                        double scale = exporterIFC.LinearScale;
                        propHnd = PropertyUtil.CreateRealPropertyFromElementOrSymbol(file, scale, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Length:
                    {
                        propHnd = PropertyUtil.CreateLengthMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.PositiveLength:
                    {
                        propHnd = PropertyUtil.CreatePositiveLengthMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.PositiveRatio:
                    {
                        propHnd = PropertyUtil.CreatePositiveRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, 
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Ratio:
                    {
                        propHnd = PropertyUtil.CreateRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, ifcPropertyName, 
                            valueType);
                        break;
                    }
                case PropertyType.PlaneAngle:
                    {
                        propHnd = PropertyUtil.CreatePlaneAngleMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, 
                            valueType);
                        break;
                    }
                case PropertyType.Area:
                    {
                        propHnd = PropertyUtil.CreateAreaMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Count:
                    {
                        propHnd = PropertyUtil.CreateCountMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Power:
                    {
                        propHnd = PropertyUtil.CreatePowerPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter, 
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ThermodynamicTemperature:
                    {
                        propHnd = PropertyUtil.CreateThermodynamicTemperaturePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ThermalTransmittance:
                    {
                        propHnd = PropertyUtil.CreateThermalTransmittancePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.VolumetricFlowRate:
                    {
                        propHnd = PropertyUtil.CreateVolumetricFlowRatePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ClassificationReference:
                    {
                        propHnd = PropertyUtil.CreateClassificationReferencePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName);
                        break;
                    }
                default:
                    throw new InvalidOperationException();
            }

            return propHnd;
        }
        public Result Execute_2(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Result commandResult = Result.Succeeded;

            try
            {
                UIApplication uiApp = commandData.Application;
                UIDocument    uiDoc = uiApp.ActiveUIDocument;
                Document      dbDoc = uiDoc.Document;
                View          view  = uiDoc.ActiveGraphicalView;

                XYZ pLoc = XYZ.Zero;

                try
                {
                    pLoc = uiDoc.Selection.PickPoint(
                        "Please pick text insertion point");
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {
                    Debug.WriteLine("Operation cancelled.");
                    message = "Operation cancelled.";

                    return(Result.Succeeded);
                }

                List <TextNoteType> noteTypeList
                    = new FilteredElementCollector(dbDoc)
                      .OfClass(typeof(TextNoteType))
                      .Cast <TextNoteType>()
                      .ToList();

                // Sort note types into ascending text size

                BuiltInParameter bipTextSize
                    = BuiltInParameter.TEXT_SIZE;

                noteTypeList.Sort((a, b)
                                  => a.get_Parameter(bipTextSize).AsDouble()
                                  .CompareTo(
                                      b.get_Parameter(bipTextSize).AsDouble()));

                foreach (TextNoteType textType in noteTypeList)
                {
                    Debug.WriteLine(textType.Name);

                    Parameter paramTextFont
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_FONT);

                    Parameter paramTextSize
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_SIZE);

                    Parameter paramBorderSize
                        = textType.get_Parameter(
                              BuiltInParameter.LEADER_OFFSET_SHEET);

                    Parameter paramTextBold
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_STYLE_BOLD);

                    Parameter paramTextItalic
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_STYLE_ITALIC);

                    Parameter paramTextUnderline
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_STYLE_UNDERLINE);

                    Parameter paramTextWidthScale
                        = textType.get_Parameter(
                              BuiltInParameter.TEXT_WIDTH_SCALE);

                    string fontName = paramTextFont.AsString();

                    double textHeight = paramTextSize.AsDouble();

                    bool textBold = paramTextBold.AsInteger() == 1
            ? true : false;

                    bool textItalic = paramTextItalic.AsInteger() == 1
            ? true : false;

                    bool textUnderline = paramTextUnderline.AsInteger() == 1
            ? true : false;

                    double textBorder = paramBorderSize.AsDouble();

                    double textWidthScale = paramTextWidthScale.AsDouble();

                    FontStyle textStyle = FontStyle.Regular;

                    if (textBold)
                    {
                        textStyle |= FontStyle.Bold;
                    }

                    if (textItalic)
                    {
                        textStyle |= FontStyle.Italic;
                    }

                    if (textUnderline)
                    {
                        textStyle |= FontStyle.Underline;
                    }

                    float fontHeightInch = (float)textHeight * 12.0f;
                    float displayDpiX    = GetDpiX();

                    float fontDpi   = 96.0f;
                    float pointSize = (float)(textHeight * 12.0 * fontDpi);

                    Font font = new Font(fontName, pointSize, textStyle);

                    int viewScale = view.Scale;

                    using (Transaction t = new Transaction(dbDoc))
                    {
                        t.Start("Test TextNote lineWidth calculation");

                        string textString = textType.Name
                                            + " (" + fontName + " "
                                            + (textHeight * 304.8).ToString("0.##") + "mm, "
                                            + textStyle.ToString() + ", "
                                            + (textWidthScale * 100.0).ToString("0.##")
                                            + "%): The quick brown fox jumps over the lazy dog.";

                        double stringWidthPx = GetStringWidth(textString, font);

                        double stringWidthIn = stringWidthPx / displayDpiX;

                        Debug.WriteLine("String Width in pixels: "
                                        + stringWidthPx.ToString("F3"));
                        Debug.WriteLine((stringWidthIn * 25.4 * viewScale).ToString("F3")
                                        + " mm at 1:" + viewScale.ToString());

                        double stringWidthFt = stringWidthIn / 12.0;

                        double lineWidth = ((stringWidthFt * textWidthScale)
                                            + (textBorder * 2.0)) * viewScale;

                        //TextNote textNote = dbDoc.Create.NewTextNote(
                        //  view, pLoc, XYZ.BasisX, XYZ.BasisY, 0.001,
                        //  TextAlignFlags.TEF_ALIGN_LEFT
                        //  | TextAlignFlags.TEF_ALIGN_TOP, textString ); // 2015
                        //textNote.TextNoteType = textType; // 2015

                        TextNote textNote = TextNote.Create(dbDoc,
                                                            view.Id, pLoc, textString, textType.Id); // 2016

                        textNote.Width = lineWidth;

                        t.Commit();
                    }

                    // Place next text note below this one with 5 mm gap

                    pLoc += view.UpDirection.Multiply(
                        (textHeight + (5.0 / 304.8))
                        * viewScale).Negate();
                }
            }
            catch (Autodesk.Revit.Exceptions.ExternalApplicationException e)
            {
                message = e.Message;
                Debug.WriteLine("Exception Encountered (Application)\n"
                                + e.Message + "\nStack Trace: " + e.StackTrace);

                commandResult = Result.Failed;
            }
            catch (Exception e)
            {
                message = e.Message;
                Debug.WriteLine("Exception Encountered (General)\n"
                                + e.Message + "\nStack Trace: " + e.StackTrace);

                commandResult = Result.Failed;
            }
            return(commandResult);
        }
Example #47
0
 /// <summary>
 /// Create new FilterRuleBuilder for current parameter
 /// </summary>
 /// <param name="curParam">Current selected parameter.</param>
 /// <returns>New FilterRuleBuilder for this parameter, null if parameter is not recognizable.</returns>
 FilterRuleBuilder CreateNewFilterRule(BuiltInParameter curParam)
 {
     StorageType paramType = m_doc.get_TypeOfStorage(curParam);
     String criteria = criteriaComboBox.SelectedItem as String;
     if (paramType == StorageType.String)
     {
         return new FilterRuleBuilder(curParam, criteria,
             ruleValueComboBox.Text, caseSensitiveCheckBox.Checked);
     }
     else if (paramType == StorageType.Double)
     {
         double ruleValue = 0, epsilon = 0;
         if (!GetRuleValueDouble(false, ref ruleValue)) return null;
         if (!GetRuleValueDouble(true, ref epsilon)) return null;
         return new FilterRuleBuilder(curParam, criteria,
             ruleValue, epsilon);
     }
     else if (paramType == StorageType.Integer)
     {
         int ruleValue = 0;
         if (!GetRuleValueInt(ref ruleValue)) return null;
         return new FilterRuleBuilder(curParam, criteria, ruleValue);
     }
     else if (paramType == StorageType.ElementId)
     {
         int ruleValue = 0;
         if (!GetRuleValueInt(ref ruleValue)) return null;
         return new FilterRuleBuilder(curParam, criteria, new ElementId(ruleValue));
     }
     else
         return null;
 }
Example #48
0
 private void SetElementParameter(FamilySymbol FamSym, BuiltInParameter paraMeter, double parameterValue)
 {
     FamSym.get_Parameter(paraMeter).Set(parameterValue);
 }
Example #49
0
 /// <summary>
 /// Check if selected parameter already in use(has criteria)
 /// </summary>
 /// <param name="selParameter">Parameter to be checked.</param>
 /// <returns>True if this parameter already has criteria, otherwise false.</returns>
 bool ParameterInUse(BuiltInParameter selParameter)
 {
     if (!HasFilterData() || m_currentFilterData.RuleData.Count == 0
         || rulesListBox.Items.Count == 0)
         return false;
     //
     // Get all existing rules and check if this parameter is in used
     int paramIndex = 0;
     bool paramIsInUse = false;
     ICollection<FilterRuleBuilder> rules = m_currentFilterData.RuleData;
     foreach (FilterRuleBuilder rule in rules)
     {
         if (rule.Parameter == selParameter)
         {
             paramIsInUse = true;
             break;
         }
         paramIndex++;
     }
     //
     // If parameter is in use, switch to this parameter and update criteria and rules
     if (paramIsInUse)
         rulesListBox.SetSelected(paramIndex, true);
     return paramIsInUse;
 }
Example #50
0
        // This function is static to make sure that no properties are used directly from the entry.
        private static IFCAnyHandle CreatePropertyFromElementBase(IFCFile file, ExporterIFC exporterIFC, Element element,
                                                                  string revitParamNameToUse, string ifcPropertyName, BuiltInParameter builtInParameter,
                                                                  PropertyType propertyType, PropertyValueType valueType, Type propertyEnumerationType)
        {
            IFCAnyHandle propHnd = null;

            switch (propertyType)
            {
            case PropertyType.Text:
            {
                propHnd = PropertyUtil.CreateTextPropertyFromElement(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                break;
            }

            case PropertyType.Label:
            {
                propHnd = PropertyUtil.CreateLabelPropertyFromElement(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                break;
            }

            case PropertyType.Identifier:
            {
                propHnd = PropertyUtil.CreateIdentifierPropertyFromElement(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Boolean:
            {
                propHnd = PropertyUtil.CreateBooleanPropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Logical:
            {
                propHnd = PropertyUtil.CreateLogicalPropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Integer:
            {
                propHnd = PropertyUtil.CreateIntegerPropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Real:
            {
                propHnd = PropertyUtil.CreateRealPropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Length:
            {
                propHnd = PropertyUtil.CreateLengthMeasurePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                              builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.PositiveLength:
            {
                propHnd = PropertyUtil.CreatePositiveLengthMeasurePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                                      builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.NormalisedRatio:
            {
                propHnd = PropertyUtil.CreateNormalisedRatioPropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                                ifcPropertyName, valueType);
                break;
            }

            case PropertyType.PositiveRatio:
            {
                propHnd = PropertyUtil.CreatePositiveRatioPropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                              ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Ratio:
            {
                propHnd = PropertyUtil.CreateRatioPropertyFromElement(file, exporterIFC, element, revitParamNameToUse, ifcPropertyName,
                                                                      valueType);
                break;
            }

            case PropertyType.PlaneAngle:
            {
                propHnd = PropertyUtil.CreatePlaneAngleMeasurePropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName,
                                                                                  valueType);
                break;
            }

            case PropertyType.PositivePlaneAngle:
            {
                propHnd = PositivePlaneAnglePropertyUtil.CreatePositivePlaneAngleMeasurePropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName,
                                                                                                            valueType);
                break;
            }

            case PropertyType.Area:
            {
                propHnd = PropertyUtil.CreateAreaMeasurePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                            builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Volume:
            {
                propHnd = PropertyUtil.CreateVolumeMeasurePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                              builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Count:
            {
                propHnd = PropertyUtil.CreateCountMeasurePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                             builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Frequency:
            {
                propHnd = FrequencyPropertyUtil.CreateFrequencyPropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                   ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ElectricCurrent:
            {
                propHnd = ElectricalCurrentPropertyUtil.CreateElectricalCurrentMeasurePropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ElectricVoltage:
            {
                propHnd = ElectricVoltagePropertyUtil.CreateElectricVoltageMeasurePropertyFromElement(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.LuminousFlux:
            {
                propHnd = PropertyUtil.CreateLuminousFluxMeasurePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                                    builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Force:
            {
                propHnd = FrequencyPropertyUtil.CreateForcePropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                               ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Pressure:
            {
                propHnd = FrequencyPropertyUtil.CreatePressurePropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                  ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ColorTemperature:
            {
                propHnd = PropertyUtil.CreateColorTemperaturePropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                 ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Currency:
            {
                propHnd = PropertyUtil.CreateCurrencyPropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                         ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ElectricalEfficacy:
            {
                propHnd = PropertyUtil.CreateElectricalEfficacyPropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                   ifcPropertyName, valueType);
                break;
            }

            case PropertyType.LuminousIntensity:
            {
                propHnd = PropertyUtil.CreateLuminousIntensityPropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                  ifcPropertyName, valueType);
                break;
            }

            case PropertyType.MassDensity:
            {
                propHnd = PropertyUtil.CreateMassDensityPropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                            ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Illuminance:
            {
                propHnd = PropertyUtil.CreateIlluminancePropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                            ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Power:
            {
                propHnd = PropertyUtil.CreatePowerPropertyFromElement(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                      ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ThermodynamicTemperature:
            {
                propHnd = PropertyUtil.CreateThermodynamicTemperaturePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                                         builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ThermalTransmittance:
            {
                propHnd = PropertyUtil.CreateThermalTransmittancePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                                     builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.VolumetricFlowRate:
            {
                propHnd = PropertyUtil.CreateVolumetricFlowRatePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                                   builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ClassificationReference:
            {
                propHnd = PropertyUtil.CreateClassificationReferencePropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                                        builtInParameter, ifcPropertyName);
                break;
            }

            case PropertyType.LinearVelocity:
            {
                propHnd = PropertyUtil.CreateLinearVelocityPropertyFromElement(file, exporterIFC, element, revitParamNameToUse,
                                                                               ifcPropertyName, valueType);
                break;
            }

            default:
                // Unhandled cases.
                return(null);
            }

            return(propHnd);
        }
        /// <summary>Gets string value from built-in parameter of an element or its type.</summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built-in parameter.</param>
        /// <param name="nullAllowed">true if we allow the property value to be empty.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <returns>The parameter, or null if not found.</returns>
        public static Parameter GetStringValueFromElementOrSymbol(Element element, BuiltInParameter builtInParameter, bool nullAllowed, out string propertyValue)
        {
            Parameter parameter = GetStringValueFromElement(element, builtInParameter, out propertyValue);
            if (parameter != null)
            {
                if (!String.IsNullOrEmpty(propertyValue))
                    return parameter;
            }

            parameter = null;
            Element elementType = element.Document.GetElement(element.GetTypeId());
            if (elementType != null)
            {
                parameter = GetStringValueFromElement(elementType, builtInParameter, out propertyValue);
                if ((parameter != null) && !nullAllowed && String.IsNullOrEmpty(propertyValue))
                    parameter = null;
            }

            return parameter;
        }
Example #52
0
 public PropertySetEntryMap(string revitParameterName, BuiltInParameter builtInParameter)
     : base(revitParameterName, builtInParameter)
 {
 }
        /// <summary>
        /// Gets element id value from parameter of an element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="builtInParameter">The built in parameter.</param>
        /// <param name="propertyValue">The output property value.</param>
        /// <returns>The parameter, or null if not found.</returns>
        public static Parameter GetElementIdValueFromElement(Element element, BuiltInParameter builtInParameter, out ElementId propertyValue)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            if (builtInParameter == BuiltInParameter.INVALID)
                throw new ArgumentException("BuiltInParameter is INVALID", "builtInParameter");

            propertyValue = ElementId.InvalidElementId;

            Parameter parameter = element.get_Parameter(builtInParameter);
            if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.ElementId)
            {
                propertyValue = parameter.AsElementId();
                return parameter;
            }

            return null;
        }
Example #54
0
        private void UpdatePluntData(List <FamilyInstance> allPlunts, ref List <FamilyInstance> failedPlunts)
        {
            const int upperZoneHeight = 1800;

            UI.ProgressBar pBar = new UI.ProgressBar("Назначение расхода", allPlunts.Count);
            foreach (FamilyInstance plunt in allPlunts)
            {
                try
                {
                    // Параметр номера помещения
                    Parameter spaceNumberParam = plunt.LookupParameter(spaceNumberParameterName);
                    // Параметр Расход воздуха
                    Parameter airflowParam = plunt.LookupParameter(airflowParameterName);
                    // Параметр "Классификация системы"
                    BuiltInParameter sysTypeBuiltIn  = BuiltInParameter.RBS_DUCT_SYSTEM_TYPE_PARAM;
                    Parameter        systemTypeParam = plunt.get_Parameter(sysTypeBuiltIn);
                    string           systemType      = systemTypeParam.AsValueString();
                    // Считаем количество диффузоров одной системы на пространство
                    int countUpperZone = (from d in allPlunts
                                          where d.LookupParameter(spaceNumberParameterName).AsString() == spaceNumberParam.AsString() &&
                                          d.get_Parameter(sysTypeBuiltIn).AsValueString() == systemType &&
                                          UnitUtils.ConvertFromInternalUnits(d.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).AsDouble(), DisplayUnitType.DUT_MILLIMETERS) >= upperZoneHeight
                                          select d).Count();
                    int countBottomZone = (from d in allPlunts
                                           where d.LookupParameter(spaceNumberParameterName).AsString() == spaceNumberParam.AsString() &&
                                           d.get_Parameter(sysTypeBuiltIn).AsValueString() == systemType &&
                                           UnitUtils.ConvertFromInternalUnits(d.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).AsDouble(), DisplayUnitType.DUT_MILLIMETERS) < upperZoneHeight
                                           select d).Count();
                    // Смещение
                    bool isInUpperZone = UnitUtils.ConvertFromInternalUnits(plunt.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).AsDouble(), DisplayUnitType.DUT_MILLIMETERS) >= upperZoneHeight;

                    // Находим пространство, в котором находится диффузор и достаем нужные значения
                    Space space = GetSpaceOfPlant(plunt);
                    if (space != null)
                    {
                        // Задаем расход диффузорам
                        double value = 0;
                        if (systemType == suplySystemTypeName)
                        {
                            value = space.get_Parameter(BuiltInParameter.ROOM_DESIGN_SUPPLY_AIRFLOW_PARAM).AsDouble();
                        }
                        else if (systemType == exhaustSystemTypeName)
                        {
                            value = space.get_Parameter(BuiltInParameter.ROOM_DESIGN_EXHAUST_AIRFLOW_PARAM).AsDouble();
                        }

                        // делим на количество диффузоров нужной системы, расположенных в одной вертикальной зоне
                        if (countUpperZone == 0 || countBottomZone == 0)
                        {
                            value = countUpperZone != 0 ? value / countUpperZone : value / countBottomZone;
                        }
                        else
                        {
                            value = isInUpperZone ? value / countUpperZone : value / countBottomZone;
                        }
                        airflowParam.Set(value);
                    }
                }
                catch
                {
                    failedPlunts.Add(plunt);
                }
                finally
                {
                    pBar.StepUp();
                }
            }
            pBar.Close();
        }
        // This function is static to make sure that no properties are used directly from the entry.
        private static IFCAnyHandle CreatePropertyFromElementOrSymbolBase(IFCFile file, ExporterIFC exporterIFC, Element element,
            string revitParamNameToUse, string ifcPropertyName, BuiltInParameter builtInParameter,
            PropertyType propertyType, PropertyValueType valueType, Type propertyEnumerationType)
        {
            IFCAnyHandle propHnd = null;

            switch (propertyType)
            {
                case PropertyType.Text:
                    {
                        propHnd = PropertyUtil.CreateTextPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                        break;
                    }
                case PropertyType.Label:
                    {
                        propHnd = PropertyUtil.CreateLabelPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                        break;
                    }
                case PropertyType.Identifier:
                    {
                        propHnd = PropertyUtil.CreateIdentifierPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Boolean:
                    {
                        propHnd = PropertyUtil.CreateBooleanPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Logical:
                    {
                        propHnd = PropertyUtil.CreateLogicalPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Integer:
                    {
                        propHnd = PropertyUtil.CreateIntegerPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Real:
                    {
                        propHnd = PropertyUtil.CreateRealPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Length:
                    {
                        propHnd = PropertyUtil.CreateLengthMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.PositiveLength:
                    {
                        propHnd = PropertyUtil.CreatePositiveLengthMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.NormalisedRatio:
                    {
                        propHnd = PropertyUtil.CreateNormalisedRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.PositiveRatio:
                    {
                        propHnd = PropertyUtil.CreatePositiveRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, 
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Ratio:
                    {
                        propHnd = PropertyUtil.CreateRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, ifcPropertyName, 
                            valueType);
                        break;
                    }
                case PropertyType.PlaneAngle:
                    {
                        propHnd = PropertyUtil.CreatePlaneAngleMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, 
                            valueType);
                        break;
                    }
                case PropertyType.PositivePlaneAngle:
                    {
                        propHnd = PositivePlaneAnglePropertyUtil.CreatePositivePlaneAngleMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName,
                            valueType);
                        break;
                    }
                case PropertyType.Area:
                    {
                        propHnd = PropertyUtil.CreateAreaMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Volume:
                    {
                        propHnd = PropertyUtil.CreateVolumeMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Count:
                    {
                        propHnd = PropertyUtil.CreateCountMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Frequency:
                    {
                        propHnd = FrequencyPropertyUtil.CreateFrequencyPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ElectricalCurrent:
                    {
                        propHnd = ElectricalCurrentPropertyUtil.CreateElectricalCurrentMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ElectricalVoltage:
                    {
                        propHnd = ElectricalVoltagePropertyUtil.CreateElectricalVoltageMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.LuminousFlux:
                    {
                        propHnd = PropertyUtil.CreateLuminousFluxMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Force:
                    {
                        propHnd = FrequencyPropertyUtil.CreateForcePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Pressure:
                    {
                        propHnd = FrequencyPropertyUtil.CreatePressurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ColorTemperature:
                    {
                        propHnd = PropertyUtil.CreateColorTemperaturePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Currency:
                    {
                        propHnd = PropertyUtil.CreateCurrencyPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ElectricalEfficacy:
                    {
                        propHnd = PropertyUtil.CreateElectricalEfficacyPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.LuminousIntensity:
                    {
                        propHnd = PropertyUtil.CreateLuminousIntensityPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Illuminance:
                    {
                        propHnd = PropertyUtil.CreateIlluminancePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.Power:
                    {
                        propHnd = PropertyUtil.CreatePowerPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter, 
                            ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ThermodynamicTemperature:
                    {
                        propHnd = PropertyUtil.CreateThermodynamicTemperaturePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ThermalTransmittance:
                    {
                        propHnd = PropertyUtil.CreateThermalTransmittancePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.VolumetricFlowRate:
                    {
                        propHnd = PropertyUtil.CreateVolumetricFlowRatePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName, valueType);
                        break;
                    }
                case PropertyType.ClassificationReference:
                    {
                        propHnd = PropertyUtil.CreateClassificationReferencePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                            builtInParameter, ifcPropertyName);
                        break;
                    }
                case PropertyType.LinearVelocity:
                    {
                       propHnd = PropertyUtil.CreateLinearVelocityPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                           ifcPropertyName, valueType);
                       break;
                    }
                default:
                    throw new InvalidOperationException();
            }

            return propHnd;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            #region Determine true north rotation

            Element projectInfoElement
                = new FilteredElementCollector(doc)
                  .OfCategory(BuiltInCategory.OST_ProjectBasePoint)
                  .FirstElement();

            BuiltInParameter bipAtn
                = BuiltInParameter.BASEPOINT_ANGLETON_PARAM;

            Parameter patn = projectInfoElement.get_Parameter(
                bipAtn);

            double atn = patn.AsDouble();

            Debug.Print(
                "Angle to north from project info: {0}",
                Util.AngleString(atn));

            #endregion // Determine true north rotation

            //ElementSet els = uidoc.Selection.Elements; // 2014

            ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); // 2015

            if (1 != ids.Count)
            {
                message = "Please select a single element.";
            }
            else
            {
                //ElementSetIterator it = els.ForwardIterator();
                //it.MoveNext();
                //Element e = it.Current as Element; // 2014

                Element e = doc.GetElement(ids.First()); // 2015

                XYZ p;
                if (!Util.GetElementLocation(out p, e))
                {
                    message
                        = "Selected element has no location defined.";

                    Debug.Print(message);
                }
                else
                {
                    string msg
                        = "Selected element location: "
                          + Util.PointString(p);

                    XYZ    pnp;
                    double x, y, pna;

                    foreach (ProjectLocation location
                             in doc.ProjectLocations)
                    {
                        //ProjectPosition projectPosition
                        //  = location.get_ProjectPosition( XYZ.Zero ); // 2017

                        ProjectPosition projectPosition
                            = location.GetProjectPosition(XYZ.Zero); // 2018

                        x   = projectPosition.EastWest;
                        y   = projectPosition.NorthSouth;
                        pnp = new XYZ(x, y, 0.0);
                        pna = projectPosition.Angle;

                        msg +=
                            "\nAngle between project north and true north: "
                            + Util.AngleString(pna);

                        // Transform tr = Transform.get_Rotation( XYZ.Zero, XYZ.BasisZ, pna ); // 2013
                        Transform tr = Transform.CreateRotation(XYZ.BasisZ, pna); // 2014

                        //Transform tt = Transform.get_Translation( pnp ); // 2013
                        Transform tt = Transform.CreateTranslation(pnp); // 2014

                        Transform t = tt.Multiply(tr);

                        msg +=
                            "\nUnrotated element location: "
                            + Util.PointString(tr.OfPoint(p)) + " "
                            + Util.PointString(tt.OfPoint(p)) + " "
                            + Util.PointString(t.OfPoint(p));

                        Util.InfoMsg(msg);
                    }
                }
            }
            return(Result.Failed);
        }
Example #57
0
        /// <summary>
        /// Get the room property value according the parameter name
        /// </summary>
        /// <param name="activeDoc">Current active document.</param>
        /// <param name="room">an instance of room class</param>
        /// <param name="paraEnum">the parameter used to get parameter value</param>
        /// <param name="useValue">convert parameter to value type or not.
        /// if true, the value of parameter will be with unit.
        /// if false, the value of parameter will be without unit.</param>
        /// <returns>the string value of property specified by shared parameter</returns>
        public static String GetProperty(Document activeDoc, Room room, BuiltInParameter paraEnum, bool useValue)
        {
            String propertyValue = null;  //the value of parameter

            // Assuming the build in parameter is legal for room.
            // if the room is not placed, some properties are not available, i.g. Level name, Area ...
            // trying to retrieve them will throw exception;
            // however some parameters are available, e.g.: name, number
            Parameter param;

            try
            {
                param = room.get_Parameter(paraEnum);
            }
            catch (Exception)
            {
                // throwing exception for this parameter is acceptable if it's a unplaced room
                if (null == room.Location)
                {
                    propertyValue = "Not Placed";
                    return(propertyValue);
                }
                else
                {
                    throw new Exception("Illegal built in parameter.");
                }
            }

            // get the parameter via the built in parameter
            if (null == param)
            {
                return("");
            }

            // get the parameter's storage type and convert parameter to string
            StorageType storageType = param.StorageType;

            switch (storageType)
            {
            case StorageType.Integer:
                int iVal = param.AsInteger();
                propertyValue = iVal.ToString();
                break;

            case StorageType.String:
                propertyValue = param.AsString();
                break;

            case StorageType.Double:
                // AsValueString will make the return string with unit, it's appreciated.
                if (useValue)
                {
                    propertyValue = param.AsValueString();
                }
                else
                {
                    propertyValue = param.AsDouble().ToString();
                }
                break;

            case StorageType.ElementId:
                Autodesk.Revit.DB.ElementId elemId = param.AsElementId();
                Element elem = activeDoc.GetElement(elemId);
                propertyValue = elem.Name;
                break;

            default:
                propertyValue = param.AsString();
                break;
            }

            return(propertyValue);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Construct a parameter filter to get only
            // unnamed reference planes, i.e. reference
            // planes whose name equals the empty string:

            BuiltInParameter bip
                = BuiltInParameter.DATUM_TEXT;

            ParameterValueProvider provider
                = new ParameterValueProvider(
                      new ElementId(bip));

            FilterStringRuleEvaluator evaluator
                = new FilterStringEquals();

            FilterStringRule rule = new FilterStringRule(
                provider, evaluator, "", false);

            ElementParameterFilter filter
                = new ElementParameterFilter(rule);

            FilteredElementCollector col
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ReferencePlane))
                  .WherePasses(filter);

            int n        = 0;
            int nDeleted = 0;

            // No need to cast ... this is pretty nifty,
            // I find ... grab the elements as ReferencePlane
            // instances, since the filter guarantees that
            // only ReferencePlane instances are selected.
            // In Revit 2014, this attempt to delete the
            // reference planes while iterating over the
            // filtered element collector throws an exception:
            // Autodesk.Revit.Exceptions.InvalidOperationException:
            // HResult=-2146233088
            // Message=The iterator cannot proceed due to
            // changes made to the Element table in Revit's
            // database (typically, This can be the result
            // of an Element deletion).
            //
            //foreach( ReferencePlane rp in col )
            //{
            //  ++n;
            //  nDeleted += DeleteIfNotHosting( rp ) ? 1 : 0;
            //}

            ICollection <ElementId> ids = col.ToElementIds();

            n = ids.Count();

            if (0 < n)
            {
                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start(string.Format(
                                 "Delete {0} ReferencePlane{1}",
                                 n, Util.PluralSuffix(n)));

                    // This also causes the exception "One or more of
                    // the elementIds cannot be deleted. Parameter
                    // name: elementIds
                    //
                    //ICollection<ElementId> ids2 = doc.Delete(
                    //  ids );
                    //nDeleted = ids2.Count();

                    List <ElementId> ids2 = new List <ElementId>(
                        ids);

                    foreach (ElementId id in ids2)
                    {
                        try
                        {
                            ICollection <ElementId> ids3 = doc.Delete(
                                id);

                            nDeleted += ids3.Count;
                        }
                        catch (Autodesk.Revit.Exceptions.ArgumentException)
                        {
                        }
                    }

                    tx.Commit();
                }
            }

            Util.InfoMsg(string.Format(
                             "{0} unnamed reference plane{1} examined, "
                             + "{2} element{3} in total were deleted.",
                             n, Util.PluralSuffix(n),
                             nDeleted, Util.PluralSuffix(nDeleted)));

            return(Result.Succeeded);
        }
        /// <summary>
        /// Use a parameter filter to return the first element
        /// of the given type and with the specified string-valued
        /// built-in parameter matching the given name.
        /// </summary>
        Element GetFirstElementOfTypeWithBipString(
            Type type,
            BuiltInParameter bip,
            string name)
        {
            FilteredElementCollector a
            = GetElementsOfType( type );

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, name, true );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              return a.WherePasses( filter ).FirstElement();
        }
Example #60
0
        /// <summary>
        /// set certain parameter of given element to int value
        /// </summary>
        /// <param name="element">given element</param>
        /// <param name="paraIndex">BuiltInParameter</param>
        /// <param name="value">the value of the parameter with integer type</param>
        /// <returns>if find the parameter return true</returns>
        public static bool SetParameter(Element element, BuiltInParameter paraIndex, int value)
        {
            //find a parameter according to the builtInParameter name
             Parameter parameter = element.get_Parameter(paraIndex);
             if (null == parameter)
             {
            return false;
             }

             if (!parameter.IsReadOnly)
             {
            StorageType parameterType = parameter.StorageType;
            if (StorageType.Integer != parameterType)
            {
               throw new Exception("The types of value and parameter are different!");
            }
            parameter.Set(value);
            return true;
             }

             return false;
        }