private static void Cleanup(Document doc)
        {
            try
            {
                const string famName             = "2020_BoundaryConditions";
                var          existingAnnotations = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                                   .OfClass(typeof(FamilyInstance))
                                                   .WhereElementIsNotElementType()
                                                   .Where(x => (doc.GetElement(x.GetTypeId()) as AnnotationSymbolType)?.FamilyName == famName)
                                                   .Select(x => x.Id)
                                                   .ToList();

                // TODO: (Konrad) Create our own Filled Region Type so that we can always find it.
                var existingRegions = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                      .OfClass(typeof(FilledRegion))
                                      .WhereElementIsNotElementType()
                                      .Where(x => (doc.GetElement(x.GetTypeId()) as FilledRegionType)?.Name == "Vertical")
                                      .Select(x => x.Id)
                                      .ToList();

                if (existingAnnotations.Any())
                {
                    doc.Delete(existingAnnotations);
                }
                if (existingRegions.Any())
                {
                    doc.Delete(existingRegions);
                }
            }
            catch (Exception e)
            {
                _logger.Fatal(e);
            }
        }
Example #2
0
        /// <summary>
        /// Retrieves all View Schedule Options in the Document. Copy paste from Revup
        /// </summary>
        public static List <ViewScheduleOption> GetViewScheduleOptions(Document doc)
        {
            List <ViewScheduleOption> options = new List <ViewScheduleOption>();

            var collector = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule));

            if (collector.Any())
            {
                var allNonCategorySchedules = collector.ToElements().Cast <ViewSchedule>().ToList().FindAll(vs => !vs.IsTemplate && vs.Definition.CategoryId == new ElementId(BuiltInCategory.OST_Sheets));
                if (allNonCategorySchedules.Any())
                {
                    foreach (var schedule in allNonCategorySchedules)
                    {
                        collector = new FilteredElementCollector(doc, schedule.Id).OfClass(typeof(ViewSheet));
                        if (collector.Any())
                        {
                            options.Add(new ViewScheduleOption()
                            {
                                Name = schedule.ViewName, Views = collector.ToElements().Cast <ViewSheet>().ToList()
                            });
                        }
                    }
                }
            }

            return(options);
        }
Example #3
0
        public List <GlazingTypeWrapper> CollectPanels()
        {
            var result = new List <GlazingTypeWrapper>();
            var panels = new FilteredElementCollector(Doc)
                         .OfClass(typeof(PanelType))
                         .WhereElementIsElementType()
                         .Cast <PanelType>()
                         .ToList();

            if (panels.Any())
            {
                var cwDoors = new FilteredElementCollector(Doc, panels.First().GetSimilarTypes())
                              .OfCategory(BuiltInCategory.OST_Doors)
                              .Cast <ElementType>()
                              .Select(x => new GlazingTypeWrapper(x, "CW Door"));

                result.AddRange(cwDoors);
            }

            result.AddRange(panels.Select(x => new GlazingTypeWrapper(x, "CW Panel")));

            var wallTypes = new FilteredElementCollector(Doc)
                            .OfClass(typeof(WallType))
                            .WhereElementIsElementType()
                            .Cast <WallType>()
                            .Where(x => x.Kind != WallKind.Curtain)
                            .Select(x => new GlazingTypeWrapper(x, "Wall"))
                            .ToList();

            result.AddRange(wallTypes);

            return(result.Except(AppSettings.Instance.StoredSettings.GeometrySettings.GlazingTypes).ToList());
        }
 private static bool IsScheduleEmpty(Autodesk.Revit.DB.ViewSchedule schedule)
 {
     using (FilteredElementCollector collector = new FilteredElementCollector(Document, schedule.Id))
     {
         return(!collector.Any());
     }
 }
Example #5
0
        /// <summary>
        /// Check Element Intersect With Element Selected By BoundingBox
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            Element element = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element));

            ExclusionFilter excludedFilter = new ExclusionFilter(new List <ElementId>()
            {
                element.Id
            });
            BoundingBoxXYZ bbxyz   = element.get_BoundingBox(doc.ActiveView);
            Outline        outline = new Outline(bbxyz.Min, bbxyz.Max);
            BoundingBoxIntersectsFilter intersectFilter = new BoundingBoxIntersectsFilter(outline);
            IList <Element>             eleIntersect    = new FilteredElementCollector(doc)
                                                          .WhereElementIsNotElementType()
                                                          .WherePasses(excludedFilter)
                                                          .WherePasses(intersectFilter).ToElements()
                                                          .Where(x => x.Category.Name != "Cameras")
                                                          .Where(x => !string.IsNullOrEmpty(x.Name)).ToList();
            StringBuilder sb = new StringBuilder();

            if (eleIntersect.Any())
            {
                foreach (Element e in eleIntersect)
                {
                    sb.AppendLine($"Name:{e.Name}-Category:{e.Category.Name}-Id:{e.Id}");
                }
            }
            MessageBox.Show($"Element Intersect : \n{sb}");
            return(Result.Succeeded);
        }
Example #6
0
 private static bool IsViewEmpty(Autodesk.Revit.DB.View view)
 {
     using (FilteredElementCollector collector = new FilteredElementCollector(Document, view.Id))
     {
         return(!collector.Any());
     }
 }
Example #7
0
 public static void Import(Document doc, string filename)
 {
     using (TransactionGroup tg = new TransactionGroup(doc, "Import Doors"))
     {
         tg.Start();
         var Lines = File.ReadAllLines(filename);
         var Doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors).ToList();
         foreach (var line in Lines)
         {
             if (Doors.Any(x => x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString() == line.Split('\t')[1]))
             {
                 var d = Doors.FirstOrDefault(x => x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString() == line.Split('\t')[1]);
                 if (d != null)
                 {
                     using (Transaction t = new Transaction(doc, "Update " + line.Split('\t')[1]))
                     {
                         t.Start();
                         var e = d as Element;
                         for (int i = 0; i < DoorParameters.Count(); i++)
                         {
                             try { e.SetElementParam(DoorParameters[i], line.Split('\t')[i + 3]); } catch { }
                         }
                         try { e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).SetValueString(line.Split('\t').Last()); } catch { }
                         t.Commit();
                     }
                 }
             }
         }
         tg.Commit();
     }
 }
Example #8
0
        /// <summary>
        /// Return the First element of the given type and name.
        /// </summary>
        public static Element GetFirstElementOfTypeNamed(Document doc, Type type, string name)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(type);

            Func <Element, bool> nameEquals = e => e.Name.Equals(name);

            return(collector.Any <Element>(nameEquals) ? collector.First <Element>(nameEquals) : null);
        }
Example #9
0
        /// <summary>
        /// 判断当前创建出来的那个实体是否与其他单元相交,如果相交,则在原实体中剪除相交的部分,如果没有相交,则直接返回原实体集合(集合中的元素个数与原 originalSolids 集合中元素个数相同)。
        /// </summary>
        /// <param name="directShape"></param>
        /// <param name="originalSolids"> directShape 所对应的实体,由于 ExecuteBooleanOperationModifyingOriginalSolid 函数中的 OriginalSolid
        /// 不能是直接从Revit的Element中得到的,所以要将前面通过轮廓拉伸出来的实体作为参数传入。</param>
        /// <param name="hasIntersect"></param>剪切后的实体的体积有可能不大于 0 啊
        /// <returns> 返回的集合中的元素个数与原 originalSolids 集合中元素个数相同。剪切后的实体的体积有可能不大于 0 .</returns>
        private IList <Solid> ExcludeIntersect(DirectShape directShape, IList <Solid> originalSolids, out bool hasIntersect)
        {
            // 应用过滤器,在整个文档中搜索与指定Element相交的Element
            FilteredElementCollector       collector     = new FilteredElementCollector(directShape.Document);
            ElementIntersectsElementFilter elementFilter = new ElementIntersectsElementFilter(element: directShape, inverted: false);

            collector.WherePasses(elementFilter);

            // 排除面层本身
            collector.Excluding(new ElementId[] { directShape.Id });

            if (!collector.Any())
            {
                // 说明没有相交的部分
                hasIntersect = false;
                return(originalSolids);
            }

            hasIntersect = true;

            // 将与其相交的实体进行剪切操作
            bool promptWhileError = false;

            foreach (Element interSectElem in collector)
            {
                var interSectSolids = GeoHelper.GetSolidsInModel(interSectElem, GeoHelper.SolidVolumnConstraint.Positive).Keys;  // 与面层对象相交的 Element 中所有的实体
                for (int i = 0; i < originalSolids.Count; i++)
                {
                    Solid originalS = originalSolids[i];

                    foreach (Solid interSectS in interSectSolids)
                    {
                        try
                        {
                            //  在原实体中减去相交的部分
                            BooleanOperationsUtils.ExecuteBooleanOperationModifyingOriginalSolid(originalS, interSectS, BooleanOperationsType.Difference);
                        }
                        catch (Exception ex)
                        {
                            if (promptWhileError)
                            {
                                // 在剪切时如果不能剪切,则不剪切。
                                DialogResult res = MessageBox.Show("实体剪切时出现错误,可能的原因是面层与模型中的其他实体有细微交叉," +
                                                                   "以致剪切后的实体出现细小锯齿。\n\r (忽略此细微交叉对于面层算量并无明显影响)。" +
                                                                   " \n\r 点击“是”以忽略并继续,点击“否”不再提示。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button2);

                                promptWhileError = (res != DialogResult.No);
                            }
                        }
                    }
                    // 剪切后的实体的体积有可能不大于 0 啊
                    originalSolids[i] = originalS;  // 将剪切完成后的 Solid 再赋值回集合中
                }
            }
            return(originalSolids);
        }
Example #10
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static Level ToRevitLevel(this oM.Geometry.SettingOut.Level level, Document document, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null)
        {
            Level revitLevel = refObjects.GetValue <Level>(document, level.BHoM_Guid);

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

            settings = settings.DefaultIfNull();

            List <Level> existingLevels = new FilteredElementCollector(document).OfClass(typeof(Level)).Cast <Level>().ToList();

            if (existingLevels.Any(x => x.Name == level.Name))
            {
                BH.Engine.Reflection.Compute.RecordError($"Level named {level.Name} could not be created because a level with the same name already exists in the model. BHoM_Guid: {level.BHoM_Guid}");
                return(null);
            }

            double elevation = level.Elevation.FromSI(UnitType.UT_Length);

            if (existingLevels.Any(x => Math.Abs(x.ProjectElevation - elevation) < settings.DistanceTolerance))
            {
                BH.Engine.Reflection.Compute.RecordError($"Level with elevation {level.Elevation} could not be created because a level with the same elevation already exists in the model. BHoM_Guid: {level.BHoM_Guid}");
                return(null);
            }

            revitLevel = Level.Create(document, elevation);
            revitLevel.CheckIfNullPush(level);
            if (revitLevel == null)
            {
                return(null);
            }

            revitLevel.Name = level.Name;

            // Copy parameters from BHoM object to Revit element
            revitLevel.CopyParameters(level, settings);

            refObjects.AddOrReplace(level, revitLevel);
            return(revitLevel);
        }
Example #11
0
        public bool IsElementVisibleInView(
            View view,
            Element el)
        {
            if (view == null)
            {
                throw new ArgumentNullException(nameof(view));
            }

            if (el == null)
            {
                throw new ArgumentNullException(nameof(el));
            }

            // Obtain the element's document.

            Document doc = el.Document;

            ElementId elId = el.Id;

            // Create a FilterRule that searches
            // for an element matching the given Id.

            FilterRule idRule = ParameterFilterRuleFactory
                                .CreateEqualsRule(
                new ElementId(BuiltInParameter.ID_PARAM),
                elId);

            var idFilter = new ElementParameterFilter(idRule);

            // Use an ElementCategoryFilter to speed up the
            // search, as ElementParameterFilter is a slow filter.

            Category cat       = el.Category;
            var      catFilter = new ElementCategoryFilter(cat.Id);

            // Use the constructor of FilteredElementCollector
            // that accepts a view id as a parameter to only
            // search that view.
            // Also use the WhereElementIsNotElementType filter
            // to eliminate element types.

            FilteredElementCollector collector =
                new FilteredElementCollector(doc, view.Id)
                .WhereElementIsNotElementType()
                .WherePasses(catFilter)
                .WherePasses(idFilter);

            // If the collector contains any items, then
            // we know that the element is visible in the
            // given view.

            return(collector.Any());
        }
Example #12
0
        /// <summary>
        /// Return the first element of the given type and name.
        /// </summary>
        public static Element GetFirstElementOfTypeNamed(
            Document doc,
            Type type,
            string name)
        {
            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfClass(type);

#if EXPLICIT_CODE
            // explicit iteration and manual checking of a property:

            Element ret = null;
            foreach (Element e in collector)
            {
                if (e.Name.Equals(name))
                {
                    ret = e;
                    break;
                }
            }
            return(ret);
#endif // EXPLICIT_CODE

#if USE_LINQ
            // using LINQ:

            IEnumerable <Element> elementsByName =
                from e in collector
                where e.Name.Equals(name)
                select e;

            return(elementsByName.First <Element>());
#endif // USE_LINQ

            // using an anonymous method:

            // if no matching elements exist, First<> throws an exception.

            //return collector.Any<Element>( e => e.Name.Equals( name ) )
            //  ? collector.First<Element>( e => e.Name.Equals( name ) )
            //  : null;

            // using an anonymous method to define a named method:

            Func <Element, bool> nameEquals = e => e.Name.Equals(name);

            return(collector.Any <Element>(nameEquals)
        ? collector.First <Element>(nameEquals)
        : null);
        }
Example #13
0
        /// <summary>
        /// Updates all of the Grid Extents objects.
        /// </summary>
        /// <param name="doc">Revit Document.</param>
        /// <param name="centralPath">Document Central File Path.</param>
        public static void CollectGridExtents(Document doc, string centralPath)
        {
            try
            {
                var grids = new FilteredElementCollector(doc)
                            .OfCategory(BuiltInCategory.OST_Grids)
                            .WhereElementIsNotElementType()
                            .ToElements()
                            .Cast <Grid>()
                            .ToList();

                // (Konrad) We are only interested in watching editable parameters. There is no need to watch them all.
                IEnumerable <ElementId> paramIds;
                if (grids.Any())
                {
                    paramIds = from Parameter param
                               in grids.First().Parameters
                               where !param.IsReadOnly
                               select param.Id;
                }
                else
                {
                    return;
                }

                if (gridParameters.ContainsKey(centralPath))
                {
                    gridParameters.Remove(centralPath);
                }
                gridParameters.Add(centralPath, paramIds);

                var extents = new Dictionary <ElementId, Outline>();
                foreach (var grid in grids)
                {
                    if (!extents.ContainsKey(grid.Id))
                    {
                        extents.Add(grid.Id, grid.GetExtents());
                    }
                }

                if (gridExtents.ContainsKey(centralPath))
                {
                    gridExtents.Remove(centralPath);
                }
                gridExtents.Add(centralPath, extents);
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }
        }
        public Family OpenFamily(Document doc, string directory, string familyName)
        {
            string path = directory + familyName + ".rfa";

            Func<Element, bool> nameEquals = e => e.Name.Equals(familyName);

            FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(Family));

            Family f = collector.Any<Element>(nameEquals) ? collector.First<Element>(nameEquals) as Family : null;

            if (f == null) doc.LoadFamily(path, out f);

            return f;
        }
Example #15
0
        public static void CreateSched(Document doc)
        {
            var schedCollector = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule)).ToList();

            if (!schedCollector.Any(x => x.Name == "DOOR SCHEDULE"))
            {
                using (Transaction t = new Transaction(doc, "Add Door Schedule"))
                {
                    t.Start();
                    var sched = ViewSchedule.CreateSchedule(doc, Category.GetCategory(doc, BuiltInCategory.OST_Doors).Id);
                    sched.Name = "DOOR SCHEDULE";

                    var Number = sched.Definition.GetSchedulableFields().FirstOrDefault(x => (BuiltInParameter)x.ParameterId.IntegerValue == BuiltInParameter.ALL_MODEL_MARK);
                    if (Number != null)
                    {
                        sched.Definition.AddField(Number);
                    }

                    var Level = sched.Definition.GetSchedulableFields().FirstOrDefault(x => (BuiltInParameter)x.ParameterId.IntegerValue == BuiltInParameter.SCHEDULE_LEVEL_PARAM);
                    if (Level != null)
                    {
                        sched.Definition.AddField(Level);
                    }

                    foreach (var sd in DoorParameters)
                    {
                        var Field = sched.Definition.GetSchedulableFields().
                                    FirstOrDefault(x => IsSharedParameterSchedulableField(doc, x.ParameterId, sd));

                        if (Field != null)
                        {
                            sched.Definition.AddField(Field);
                        }
                    }

                    var Comments = sched.Definition.GetSchedulableFields().FirstOrDefault(x => (BuiltInParameter)x.ParameterId.IntegerValue == BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
                    if (Comments != null)
                    {
                        sched.Definition.AddField(Comments);
                    }

                    t.Commit();
                }
            }
            else
            {
                TaskDialog.Show("Error", "The Schedule Already Exists");
            }
        }
Example #16
0
        /// <summary>
        /// Tries to find a level by ELEVATION only, otherwise it creates it.
        /// Unless it was created with schema builder and has `referenceOnly=true`, in which case it gets it by name only
        /// Reason for this approach, take the example below:
        /// source file has L0 @0m and L1 @4m
        /// dest file has L1 @0m and L2 @4m
        /// attempting to move or rename levels would just be a mess, hence, we don't do that!
        /// </summary>
        /// <param name="speckleLevel"></param>
        /// <returns></returns>
        public Level LevelToNative(BuiltElements.Level speckleLevel)
        {
            if (speckleLevel == null)
            {
                return(null);
            }
            var docLevels = new FilteredElementCollector(Doc).OfClass(typeof(DB.Level)).ToElements().Cast <DB.Level>();

            // it's a level created with schema builder for reference only
            // we only try to match it by name
            var rl = speckleLevel as RevitLevel;

            if (rl != null && rl.referenceOnly)
            {
                var existingLevel = docLevels.FirstOrDefault(docLevel => docLevel.Name == speckleLevel.name);
                if (existingLevel != null)
                {
                    return(existingLevel);
                }
                else
                {
                    ConversionErrors.Add(new Error {
                        message = $"Could not find level '{speckleLevel.name}' in this document."
                    });
                    return(null);
                }
            }

            var speckleLevelElevation    = ScaleToNative((double)speckleLevel.elevation, speckleLevel.units);
            var existingLevelByElevation = docLevels.FirstOrDefault(l => Math.Abs(l.Elevation - (double)speckleLevelElevation) < 0.0164042);

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

            // If we don't have an existing level, create it.
            var level = Level.Create(Doc, (double)speckleLevelElevation);

            if (!docLevels.Any(x => x.Name == speckleLevel.name))
            {
                level.Name = speckleLevel.name;
            }
            if (rl != null && rl.createView)
            {
                CreateViewPlan(speckleLevel.name, level.Id);
            }
            return(level);
        }
Example #17
0
        private void BtChangeOnView_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (CopingDistanceValue.Value.HasValue)
                {
                    Hide();
                    var distanceValue = CopingDistanceValue.Value;
                    var doc           = _uiApplication.ActiveUIDocument.Document;
                    var elements      = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                        .OfCategory(BuiltInCategory.OST_StructuralFraming).WhereElementIsNotElementType().ToElements();
                    if (elements.Any())
                    {
                        using (var tr = new Transaction(
                                   _uiApplication.ActiveUIDocument.Document,
                                   ModPlusAPI.Language.GetItem(LangItem, "h9")))
                        {
                            tr.Start();
                            foreach (var el in elements)
                            {
                                var parameter = el.get_Parameter(BuiltInParameter.STRUCTURAL_COPING_DISTANCE);
                                parameter?.Set(distanceValue.Value.MmToFt());
                            }

                            tr.Commit();
                        }
                    }
                }
                else
                {
                    ModPlusAPI.Windows.MessageBox.Show(
                        ModPlusAPI.Language.GetItem(LangItem, "h10"), //// "Введено некорректное значение!"
                        MessageBoxIcon.Alert);
                }
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                // ignore
            }
            catch (Exception exception)
            {
                ExceptionBox.Show(exception);
            }
            finally
            {
                ShowDialog();
            }
        }
Example #18
0
        //private SlabEdgeTypes() : base("Slab Edge Type") { }

        protected override SelectionState PopulateItemsCore(string currentSelection)
        {
            Items.Clear();
            //find all sheets in the project
            var elements = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument).OfClass(typeof(SlabEdgeType)).ToElements();

            Console.WriteLine(elements);
            if (!elements.Any())
            {
                Items.Add(new DynamoDropDownItem(noSlabEdge, null));
                SelectedIndex = 0;
                return(SelectionState.Done);
            }
            Items = elements.Select(x => new DynamoDropDownItem((x.Name), x)).OrderBy(x => x.Name).ToObservableCollection();
            return(SelectionState.Restore);
        }
Example #19
0
        /// <summary>
        ///    Alle elementen bepalen, dus niet alleen de elementen uit de actieve view
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public static List <Element> GetAllProjectElements(Document doc)
        {
            List <Element>           elementList;
            FilteredElementCollector elemTypeCtor    = (new FilteredElementCollector(doc)).WhereElementIsElementType();
            FilteredElementCollector notElemTypeCtor = (new FilteredElementCollector(doc)).WhereElementIsNotElementType();
            FilteredElementCollector allElementCtor  = elemTypeCtor.UnionWith(notElemTypeCtor);

            try
            {
                elementList = !allElementCtor.Any() ? new List <Element>() : allElementCtor.ToList();
            }
            catch
            {
                elementList = new List <Element>();
            }
            return(elementList);
        }
Example #20
0
        public static void CreateSched(Document doc)
        {
            var schedCollector = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule)).ToList();

            if (!schedCollector.Any(x => x.Name == "FINISH LEGEND"))
            {
                using (Transaction t = new Transaction(doc, "Add Material Schedule"))
                {
                    t.Start();
                    var sched = ViewSchedule.CreateMaterialTakeoff(doc, ElementId.InvalidElementId);
                    sched.Name = "FINISH LEGEND";

                    var Mark = sched.Definition.GetSchedulableFields()
                               .Where(x => x.FieldType == ScheduleFieldType.Material)
                               .FirstOrDefault(x => (BuiltInParameter)x.ParameterId.IntegerValue == BuiltInParameter.ALL_MODEL_MARK);
                    if (Mark != null)
                    {
                        sched.Definition.AddField(Mark);
                    }

                    foreach (var sd in MatPars)
                    {
                        var Field = sched.Definition.GetSchedulableFields().
                                    Where(x => x.FieldType == ScheduleFieldType.Material).
                                    FirstOrDefault(x => IsSharedParameterSchedulableField(doc, x.ParameterId, sd));

                        if (Field != null)
                        {
                            sched.Definition.AddField(Field);
                        }
                    }

                    t.Commit();
                }
            }
            else
            {
                TaskDialog.Show("Error", "The Schedule Already Exists");
            }
        }
Example #21
0
        /// <summary>
        /// Collects all of the imported styles in the model.
        /// </summary>
        private void CollectStyles()
        {
            var wrappers = new ObservableCollection <CategoryWrapper>();

            var allStyles = new FilteredElementCollector(_doc)
                            .OfClass(typeof(GraphicsStyle))
                            .Cast <GraphicsStyle>()
                            .ToList();

            if (!allStyles.Any())
            {
                return;
            }

            foreach (var style in allStyles)
            {
                if (style.GraphicsStyleCategory.Name.Contains(".dwg"))
                {
                    var subCats = style.GraphicsStyleCategory.SubCategories;
                    foreach (Category subCat in subCats)
                    {
                        wrappers.Add(new CategoryWrapper(subCat)
                        {
                            ParentName = style.GraphicsStyleCategory.Name
                        });
                    }
                }
                else if (style.Name == "Imports in Families")
                {
                    var subCats = style.GraphicsStyleCategory.SubCategories;
                    foreach (Category subCat in subCats)
                    {
                        wrappers.Add(new CategoryWrapper(subCat));
                    }
                }
            }

            Styles = new ObservableCollection <CategoryWrapper>(wrappers.OrderBy(x => x.Name));
        }
        /// <inheritdoc />
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
#if !DEBUG
            Statistic.SendCommandStarting(new ModPlusConnector());
#endif
            RevitEvent    = new RevitEvent();
            UiApplication = commandData.Application;

            if (commandData.View is ViewSchedule)
            {
                var el = new FilteredElementCollector(commandData.View.Document, commandData.View.Id)
                         .WhereElementIsNotElementType()
                         .Where(e => e.IsValidObject);
                if (!el.Any())
                {
                    MessageBox.Show(Language.GetItem("m2"));
                    return(Result.Cancelled);
                }

                var win     = new View.InScheduleWindow();
                var context = new InScheduleContext(win, commandData.Application);
                win.DataContext      = context;
                win.ContentRendered += (sender, args) => context.Initialize();
                ModPlus.ShowModal(win);
            }
            else
            {
                var selection           = commandData.Application.ActiveUIDocument.Selection;
                var doc                 = commandData.Application.ActiveUIDocument.Document;
                var preSelectedElements = selection.GetElementIds().Select(id => doc.GetElement(id)).ToList();
                var win                 = new View.InViewWindow();
                var context             = new InViewContext(win, commandData.Application);
                win.DataContext      = context;
                win.ContentRendered += (sender, args) => context.Initialize(preSelectedElements);
                ModPlus.ShowModeless(win);
            }

            return(Result.Succeeded);
        }
Example #23
0
        protected override SelectionState PopulateItemsCore(string currentSelection)
        {
            Items.Clear();

            var elements = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument)
                           .OfClass(typeof(Autodesk.Revit.DB.RoofType))
                           .ToElements();

            if (!elements.Any())
            {
                Items.Add(new DynamoDropDownItem(Properties.Resources.NoWallTypesAvailable, null));

                SelectedIndex = 0;
                return(SelectionState.Done);
            }

            Items = elements
                    .Select(x => new DynamoDropDownItem(x.Name, x))
                    .OrderBy(x => x.Name)
                    .ToObservableCollection();

            return(SelectionState.Restore);
        }
Example #24
0
        private bool LevelPassesFilter(Room room)
        {
            if (co == ComparisonOperator.Equals)
            {
                return(room.Level.Name == test);
            }

            if (co == ComparisonOperator.Contains)
            {
                return(room.Level.Name.Contains(test));
            }

            var collector = new FilteredElementCollector(room.Document)
                            .OfClass(typeof(Level))
                            .Cast <Level>()
                            .Where(lvl => lvl.Name == test);

            if (collector.Any())
            {
                double elev = collector.First().Elevation;
                {
                    int p = room.Level.Elevation.CompareTo(elev);
                    switch (co)
                    {
                    case ComparisonOperator.LessThan:
                        return(p < 0);

                    case ComparisonOperator.GreaterThan:
                        return(p > 0);

                    case ComparisonOperator.NotEqual:
                        return(p != 0);
                    }
                }
            }
            return(false);
        }
        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;

              Transaction t = new Transaction( doc );

              t.Start( "Create Steel Stair Beams" );

              // Check whether the required family is loaded:

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .OfClass( typeof( Family ) );

              // If the family is not already loaded, do so:

              if( !collector.Any<Element>(
            e => e.Name.Equals( FamilyName ) ) )
              {
            FamilySymbol symbol;

            if( !doc.LoadFamilySymbol(
              _family_path, SymbolName, out symbol ) )
            {
              message = string.Format(
            "Unable to load '{0}' from '{1}'.",
            SymbolName, _family_path );

              t.RollBack();

              return Result.Failed;
            }
              }

              try
              {
            // Create a couple of connected beams:

            SteelStairs s = new SteelStairs( doc );

            s.Run();

            t.Commit();

            return Result.Succeeded;
              }
              catch( Exception ex )
              {
            message = ex.Message;

            t.RollBack();

            return Result.Failed;
              }
        }
Example #26
0
 public static void Import(Document doc, string filename)
 {
     using (TransactionGroup tg = new TransactionGroup(doc, "Add Materials"))
     {
         Family fam;
         tg.Start();
         using (Transaction t = new Transaction(doc, "Load Family"))
         {
             t.Start();
             fam = EmbeddedFamilies.run(doc, "MaterialInstance");
             t.Commit();
         }
         FamilySymbol symbol = doc.GetElement(fam.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
         if (!symbol.IsActive)
         {
             using (Transaction t = new Transaction(doc, "Activate Symbol"))
             {
                 t.Start();
                 symbol.Activate(); doc.Regenerate();
                 t.Commit();
             }
         }
         var Lines   = File.ReadAllLines(filename);
         var Mats    = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Materials).ToList();
         var GenMods = GetGenericModels(doc, fam);
         foreach (var line in Lines)
         {
             if (Mats.Any(x => x.Name == line.Split('\t')[1]))
             {
                 var m = Mats.FirstOrDefault(x => x.Name == line.Split('\t')[1]);
                 if (m != null)
                 {
                     using (Transaction t = new Transaction(doc, "Update Material : " + m.Name))
                     {
                         t.Start();
                         var e = m as Element;
                         for (int i = 0; i < MatPars.Count(); i++)
                         {
                             try { e.SetElementParam(MatPars[i], line.Split('\t')[i + 2]); } catch { }
                         }
                         t.Commit();
                     }
                 }
                 if (!GenMods.Any(x => x.GetElementParam(SpecialParams.MaterialInstance) == line.Split('\t')[1]))
                 {
                     using (Transaction t = new Transaction(doc, "Place Material : " + line.Split('\t')[1]))
                     {
                         t.Start();
                         FamilyInstance f = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), doc.GetElement(fam.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol, StructuralType.NonStructural);
                         f.SetElementParam(SpecialParams.MaterialInstance, line.Split('\t')[1]);
                         t.Commit();
                     }
                 }
             }
             else
             {
                 using (Transaction t = new Transaction(doc, "Create Material : " + line.Split('\t')[1]))
                 {
                     t.Start();
                     ElementId matID = Material.Create(doc, line.Split('\t')[1]);
                     Element   mat   = doc.GetElement(matID);
                     for (int i = 0; i < MatPars.Count(); i++)
                     {
                         try { mat.SetElementParam(MatPars[i], line.Split('\t')[i + 2]); } catch { }
                     }
                     doc.Regenerate();
                     t.Commit();
                 }
                 using (Transaction t = new Transaction(doc, "Place Material : " + line.Split('\t')[1]))
                 {
                     t.Start();
                     FamilyInstance f = doc.Create.NewFamilyInstance(new XYZ(0, 0, 0), doc.GetElement(fam.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol, StructuralType.NonStructural);
                     f.SetElementParam(SpecialParams.MaterialInstance, line.Split('\t')[1]);
                     t.Commit();
                 }
             }
         }
         if (GenMods.Any())
         {
             List <ElementId> del = new List <ElementId>();
             foreach (var g in GenMods)
             {
                 if (!Lines.Any(x => x.Split('\t')[1] == g.GetElementParam(SpecialParams.MaterialInstance)))
                 {
                     del.Add(g.Id);
                 }
             }
             using (Transaction t = new Transaction(doc, "Delete Materials"))
             {
                 t.Start();
                 doc.Delete(del);
                 t.Commit();
             }
         }
         tg.Commit();
     }
 }
Example #27
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;

            Transaction t = new Transaction(doc);

            t.Start("Create Steel Stair Beams");

            // Check whether the required family is loaded:

            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(Family));

            // If the family is not already loaded, do so:

            if (!collector.Any <Element>(
                    e => e.Name.Equals(FamilyName)))
            {
                FamilySymbol symbol;

                if (!doc.LoadFamilySymbol(
                        _family_path, SymbolName, out symbol))
                {
                    message = string.Format(
                        "Unable to load '{0}' from '{1}'.",
                        SymbolName, _family_path);

                    t.RollBack();

                    return(Result.Failed);
                }
            }

            try
            {
                // Create a couple of connected beams:

                SteelStairs s = new SteelStairs(doc);

                s.Run();

                t.Commit();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;

                t.RollBack();

                return(Result.Failed);
            }
        }
Example #28
0
        public void FillTreeView()
        {
            List <Category>          categories     = new List <Category>();
            List <HashSet <String> > parametersList = new List <HashSet <String> >();
            List <FamilyInstance>    familyInstances;
            FamilySymbol             familySymbol;
            Family family;

            this.treeView1.BeginUpdate();
            foreach (Category category in this.FormDoc.Settings.Categories)
            {
                if (category.AllowsBoundParameters &&
                    category.get_AllowsVisibilityControl(this.FormDoc.ActiveView))
                {
                    familyInstances = new FilteredElementCollector(this.FormDoc)
                                      .OfClass(typeof(FamilyInstance))
                                      .OfCategoryId(category.Id)
                                      .ToElements()
                                      .Cast <FamilyInstance>()
                                      .ToList();

                    if (!familyInstances.Any())
                    {
                        continue;
                    }

                    categories.Add(category);
                    treeView1.Nodes.Add(category.Name);

                    // set of parameters
                    HashSet <String> parameters = new HashSet <String>();

                    foreach (FamilyInstance familyInstance in familyInstances)
                    {
                        familySymbol = familyInstance.Symbol;
                        family       = familySymbol.Family;

                        foreach (Parameter parameter in familyInstance.Parameters)
                        {
                            // add instance parameters to set
                            parameters.Add(parameter.Definition.Name);
                        }

                        //foreach (Parameter parameter in familySymbol.Parameters)
                        //{
                        //    // add type parameters to set
                        //    parameters.Add(parameter.Definition.Name);
                        //}

                        //foreach (Parameter parameter in family.Parameters)
                        //{
                        //    // add family type parameter to set
                        //    parameters.Add(parameter.Definition.Name);
                        //}
                    }

                    foreach (String parameter in parameters)
                    {
                        treeView1.Nodes[categories.IndexOf(category)].Nodes.Add(parameter);
                    }

                    // add parameter set to list
                    parametersList.Add(parameters);
                }
            }
            this.treeView1.EndUpdate();
        }
Example #29
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;

            // Initializing variables
            // categories dic to recognize choosen categories
            Dictionary <string, Category> categoriesDic = new Dictionary <string, Category>();
            List <string> categoryNames = new List <string>();

            // categories exception, which are not to be deleted
            List <string> categoryExceptions = new List <string>()
            {
                "Níveis",
                "Informações do projeto",
                "Materiais",
                "Vistas",
                "Tabelas",
                "Itens de detalhe",
                "Vínculos RVT"
            };

            // populating categoryNames and categoriesDic
            foreach (Category category in doc.Settings.Categories)
            {
                if (category.AllowsBoundParameters)
                {
                    categoryNames.Add(category.Name);
                    categoriesDic.Add(category.Name, category);
                }
            }

            // categories deletion try count to count how many times it was tryed to delete each category
            List <int> zeros = new List <int>(new int[categoriesDic.Count]);
            Dictionary <string, int> categoriesDeletionTryCount = categoriesDic.Keys.Zip(zeros, (k, v) => new { k, v })
                                                                  .ToDictionary(x => x.k, x => x.v);

            // sorting categoryNames to show in GUI
            categoryNames.Sort();

            // creating selectFromList instance, show it and get its result
            SelectFromList selectFromList = new SelectFromList(categoryNames);

            System.Windows.Forms.DialogResult dialogResult = selectFromList.ShowDialog();
            List <string> selectedCategories = selectFromList.GetSelectedItems();

            if (dialogResult == System.Windows.Forms.DialogResult.OK)
            {
                // main loop, iterating over categories trying to delete them, until none of them least or max attempt achived
                Category category;
                string   categoriesDeleted        = "";
                string   categoriesNotDeleted     = "";
                string   categoriesNotToBeDeleted = "";
                while (true)
                {
                    if (!selectedCategories.Any())
                    {
                        break;
                    }
                    if (categoryExceptions.Contains(selectedCategories[0]))
                    {
                        categoriesNotToBeDeleted += "  -" + selectedCategories[0] + "\n";
                        selectedCategories.RemoveAt(0);
                    }
                    else
                    {
                        categoriesDic.TryGetValue(selectedCategories[0], out category);
                        Transaction t = new Transaction(doc, "Limpar " + category.Name);
                        // trying to delete category elements
                        try
                        {
                            var elementIds = new FilteredElementCollector(doc)
                                             .OfCategoryId(category.Id)
                                             .WhereElementIsNotElementType()
                                             .ToElementIds();
                            if (elementIds.Any())
                            {
                                t.Start();
                                doc.Delete(elementIds);
                                t.Commit();
                                categoriesDeleted += "  -" + category.Name + "\n";
                            }
                            selectedCategories.Remove(category.Name);
                        }
                        catch (Exception)
                        {
                            // if not possible, handle it
                            t.RollBack();
                            selectedCategories.Remove(category.Name);
                            // adding in the category.Name count
                            categoriesDeletionTryCount[category.Name] += 1;
                            // at least 8 attempts to delete
                            if (categoriesDeletionTryCount[category.Name] < 8)
                            {
                                selectedCategories.Add(category.Name);
                            }
                            else
                            {
                                categoriesNotDeleted += "  -" + category.Name + "\n";
                            }
                        }
                    }
                }
                string text = "";
                if (categoriesDeleted.Any())
                {
                    text += "Categorias excluídas: \n" + categoriesDeleted;
                }
                if (categoriesNotDeleted.Any())
                {
                    text += "\nCategorias que não puderam ser excluídas: \n" + categoriesNotDeleted;
                }
                if (categoriesNotToBeDeleted.Any())
                {
                    text += "\nCategorias que não devem ser excluídas: \n" + categoriesNotToBeDeleted;
                }
                ToolExtract toolExtract = new ToolExtract(text);
                toolExtract.ShowDialog();

                return(Result.Succeeded);
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Limpar projeto foi cancelado.", "Limpar projeto");
            }
            return(Result.Cancelled);
        }
Example #30
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
#if !DEBUG
            Statistic.SendCommandStarting("mprRebarsWithoutHost", new ModPlusConnector().AvailProductExternalVersion);
#endif
            try
            {
                var doc = commandData.Application.ActiveUIDocument.Document;

                IList <Rebar> rebars = new FilteredElementCollector(doc)
                                       .OfClass(typeof(Rebar))
                                       .WhereElementIsNotElementType()
                                       .Where(x => x.IsValidObject && x.Category != null)
                                       .Cast <Rebar>()
                                       .ToList();
                IList <RebarInSystem> rebarInSystems = new FilteredElementCollector(doc)
                                                       .OfClass(typeof(RebarInSystem))
                                                       .WhereElementIsNotElementType()
                                                       .Where(x => x.IsValidObject && x.Category != null)
                                                       .Cast <RebarInSystem>()
                                                       .ToList();

                var taskDialog = new TaskDialog(Language.GetItem(LangItem, "h17"));
                if (!rebars.Any() && !rebarInSystems.Any())
                {
                    // В текущем проекте не найдена арматура
                    taskDialog.MainContent = Language.GetItem(LangItem, "m2");
                    taskDialog.Show();
                    return(Result.Cancelled);
                }

                taskDialog.MainContent =
                    //// В текущем проекте найдено:
                    $"{Language.GetItem(LangItem, "m3")}{Environment.NewLine}{Language.GetItem(LangItem, "m4")} {rebars.Count}{Environment.NewLine}{Language.GetItem(LangItem, "m5")} {rebarInSystems.Count}";

                taskDialog.AddCommandLink(
                    TaskDialogCommandLinkId.CommandLink1,
                    //// Выполнить проверку
                    Language.GetItem(LangItem, "m6"));
                var dialogResult = taskDialog.Show();

                if (dialogResult == TaskDialogResult.CommandLink1)
                {
                    taskDialog = new TaskDialog(Language.GetItem(LangItem, "h17"));
                    //// Результат проверки:
                    taskDialog.MainContent = Language.GetItem(LangItem, "m7");

                    // для кэширования
                    var hostDictionary = new Dictionary <int, List <Solid> >();

                    var outsideHostRebars  = new List <ElementId>();
                    var noHostRebars       = new List <ElementId>();
                    var systemsOutsideHost = new List <ElementId>();

                    foreach (var rebar in rebars)
                    {
                        var hostId = rebar.GetHostId();
                        if (hostId == ElementId.InvalidElementId)
                        {
                            noHostRebars.Add(rebar.Id);
                        }
                        else
                        {
                            var hostSolids = GetHostSolids(hostDictionary, hostId, doc);

                            var rebarCurves =
                                rebar.GetCenterlineCurves(false, false, false, MultiplanarOption.IncludeAllMultiplanarCurves, 0)
                                .ToList();

                            if (rebar.LayoutRule == RebarLayoutRule.Single)
                            {
                                if (!IntersectWithSolids(rebarCurves, hostSolids))
                                {
                                    outsideHostRebars.Add(rebar.Id);
                                }
                            }
                            else
                            {
                                if (HasOutsideCurves(rebarCurves, hostSolids))
                                {
                                    outsideHostRebars.Add(rebar.Id);
                                }
                            }
                        }
                    }

                    foreach (var rebarInSystem in rebarInSystems)
                    {
                        var hostId = rebarInSystem.GetHostId();
                        if (hostId == ElementId.InvalidElementId)
                        {
                            noHostRebars.Add(rebarInSystem.Id);
                        }
                        else
                        {
                            var systemCurves = rebarInSystem.GetCenterlineCurves(false, false, false).ToList();
                            var hostSolids   = GetHostSolids(hostDictionary, hostId, doc);
                            if (HasOutsideCurves(systemCurves, hostSolids))
                            {
                                systemsOutsideHost.Add(rebarInSystem.Id);
                            }
                        }
                    }

                    var selectAll     = false;
                    var allElementIds = new List <ElementId>();

                    if (outsideHostRebars.Any())
                    {
                        // Арматурные стержни, находящиеся вне основы или выступающие за основу (при компоновке):
                        taskDialog.MainContent +=
                            $"{Environment.NewLine}{Language.GetItem(LangItem, "m8")} {outsideHostRebars.Count}";

                        // Выбрать арматурные стержни
                        taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, Language.GetItem(LangItem, "m9"));
                        if (noHostRebars.Any() || systemsOutsideHost.Any())
                        {
                            selectAll = true;
                        }
                    }

                    if (noHostRebars.Any())
                    {
                        // Арматура, не имеющая основы:
                        taskDialog.MainContent +=
                            $"{Environment.NewLine}{Language.GetItem(LangItem, "m10")} {noHostRebars.Count}";

                        // Выбрать арматурные стержни
                        taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, Language.GetItem(LangItem, "m9"));
                        if (outsideHostRebars.Any() || systemsOutsideHost.Any())
                        {
                            selectAll = true;
                        }
                    }

                    if (systemsOutsideHost.Any())
                    {
                        // Арматурные стержни в системе, выступающие за основу:
                        taskDialog.MainContent +=
                            $"{Environment.NewLine}{Language.GetItem(LangItem, "m11")} {systemsOutsideHost.Count}";

                        // Выбрать системы
                        taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, Language.GetItem(LangItem, "m12"));
                        if (outsideHostRebars.Any() || noHostRebars.Any())
                        {
                            selectAll = true;
                        }
                    }

                    if (selectAll)
                    {
                        allElementIds.AddRange(outsideHostRebars);
                        allElementIds.AddRange(noHostRebars);
                        allElementIds.AddRange(systemsOutsideHost);

                        // Выбрать все
                        taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink4, Language.GetItem(LangItem, "m13"));
                    }

                    if (!outsideHostRebars.Any() && !noHostRebars.Any() && !systemsOutsideHost.Any())
                    {
                        // Ничего не найдено
                        taskDialog.MainContent += Environment.NewLine + Language.GetItem(LangItem, "m14");
                    }

                    dialogResult = taskDialog.Show();

                    if (dialogResult == TaskDialogResult.CommandLink1)
                    {
                        commandData.Application.ActiveUIDocument.Selection.SetElementIds(outsideHostRebars);
                    }

                    if (dialogResult == TaskDialogResult.CommandLink2)
                    {
                        commandData.Application.ActiveUIDocument.Selection.SetElementIds(noHostRebars);
                    }

                    if (dialogResult == TaskDialogResult.CommandLink3)
                    {
                        commandData.Application.ActiveUIDocument.Selection.SetElementIds(systemsOutsideHost);
                    }

                    if (dialogResult == TaskDialogResult.CommandLink4)
                    {
                        commandData.Application.ActiveUIDocument.Selection.SetElementIds(allElementIds);
                    }
                }
            }
            catch (Exception exception)
            {
                ExceptionBox.Show(exception);
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// Certain Categories like Stairs contain elements of different Categories, that are hosted
        /// to them. We need to handle these approprietely.
        /// </summary>
        /// <param name="doc">Document</param>
        /// <param name="catInfo">Category Info object.</param>
        /// <param name="element">Element to check.</param>
        private static void RunCategoryAction(Document doc, CategoryInfo catInfo, Element element)
        {
            try
            {
                switch (catInfo.BltCategory)
                {
                case BuiltInCategory.OST_Topography:
                    var surface      = (TopographySurface)element;
                    var subRegionIds = surface.GetHostedSubRegionIds();
                    if (subRegionIds?.Count > 0)
                    {
                        foreach (var eId in subRegionIds)
                        {
                            var subRegion = doc.GetElement(eId);
                            if (null != subRegion)
                            {
                                CreateDirectShape(doc, subRegion);
                            }
                        }
                    }
                    break;

                case BuiltInCategory.OST_Stairs:
                    if (Stairs.IsByComponent(doc, element.Id))
                    {
                        var stair      = (Stairs)element;
                        var railingIds = stair.GetAssociatedRailings();
                        if (railingIds.Count > 0)
                        {
                            foreach (var eId in railingIds)
                            {
                                var railing = doc.GetElement(eId);
                                if (null != railing)
                                {
                                    CreateDirectShape(doc, railing);
                                }
                            }
                        }
                    }
                    else
                    {
                        var railings = new FilteredElementCollector(doc)
                                       .OfClass(typeof(Railing))
                                       .WhereElementIsNotElementType()
                                       .Cast <Railing>()
                                       .Where(x => x.HasHost && x.HostId == element.Id)
                                       .ToList();

                        if (railings.Any())
                        {
                            foreach (var railing in railings)
                            {
                                CreateDirectShape(doc, railing);
                            }
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message + "-" + element.Id);
            }
        }