/// <summary> /// Filter Element By Categories /// </summary> /// <param name="doc"></param> /// <param name="categoryNames"></param> /// <returns></returns> public static ElementFilter FiltersElementByCategory(this Document doc, IEnumerable <string> categoryNames) { ElementFilter categoriesFilter = null; if (categoryNames != null && categoryNames.Any()) { var categoryIds = new List <ElementId>(); foreach (var categoryName in categoryNames) { var category = doc.Settings.Categories.get_Item(categoryName); if (category != null) { categoryIds.Add(category.Id); } } var categoryFilters = new List <ElementFilter>(); if (categoryIds.Count > 0) { var categoryRule = new FilterCategoryRule(categoryIds); var categoryFilter = new ElementParameterFilter(categoryRule); categoryFilters.Add(categoryFilter); } if (categoryFilters.Count > 0) { categoriesFilter = new LogicalOrFilter(categoryFilters); } } return(categoriesFilter); }
public virtual Element FindMethodElement(Type type, string methodName) { TypeMirror mirror = _typeMirrorTestUtils.typeOf(type); //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: return(ElementFilter.methodsIn(_types.asElement(mirror).EnclosedElements).Where(method => method.SimpleName.contentEquals(methodName)).First().orElseThrow(() => new AssertionError(string.Format("Could not find method {0} of class {1}", methodName, type.FullName)))); }
public void IsMatchNameTest() { ElementFilter filter = new ElementFilter("$(Name) : 'Style'"); // // Not a match // FieldElement noMatch = new FieldElement(); noMatch.Name = "Test"; Assert.IsFalse(filter.IsMatch(noMatch), "IsMatch did not return the expected value."); // // Match // FieldElement match = new FieldElement(); match.Name = "Style"; Assert.IsTrue(filter.IsMatch(match), "IsMatch did not return the expected value."); match.Name = "ElementStyle"; Assert.IsTrue(filter.IsMatch(match), "IsMatch did not return the expected value."); match.Name = "StyleElement"; Assert.IsTrue(filter.IsMatch(match), "IsMatch did not return the expected value."); // // Null // Assert.IsFalse(filter.IsMatch(null), "IsMatch did not return the expected value."); }
private IList <ElementFilter> CollectFilters(ComboBox[,] comboBoxs) { IList <ElementFilter> filters = new List <ElementFilter>(); for (int i = 0; i < 4; i++) { string parameter = comboBoxs[i, 0]?.SelectedValue?.ToString(); string operat = comboBoxs[i, 1]?.SelectedValue?.ToString(); if (parameter != null && operat != null) { ElementFilter f = CreateParameterFilter.createParameterFilter( DOC, (ParameterData)comboBoxs[i, 0].SelectedValue, comboBoxs[i, 1].SelectedValue.ToString(), comboBoxs[i, 2].Text); if (f != null) { filters.Add(f); } } } return(filters); }
public void IsMatchAccessTest() { ElementFilter filter = new ElementFilter("$(Access) : 'Protected'"); // // Not a match // FieldElement publicField = new FieldElement(); publicField.Access = CodeAccess.Public; Assert.IsFalse(filter.IsMatch(publicField), "IsMatch did not return the expected value."); // // Match // FieldElement protectedField = new FieldElement(); protectedField.Access = CodeAccess.Protected; Assert.IsTrue(filter.IsMatch(protectedField), "IsMatch did not return the expected value."); // // Multi flag // FieldElement protectedInternalField = new FieldElement(); protectedInternalField.Access = CodeAccess.Protected | CodeAccess.Internal; Assert.IsTrue(filter.IsMatch(protectedInternalField), "IsMatch did not return the expected value."); // // Null // Assert.IsFalse(filter.IsMatch(null), "IsMatch did not return the expected value."); }
private bool CreateFiltersIfMissing(Document doc) { if (curLODfilter != null && tarLODfilter != null) { return(false); } ElementId val = LODapp.GetLODparameter(doc, "Current_LOD").get_Id(); ElementId val2 = LODapp.GetLODparameter(doc, "Target_LOD").get_Id(); ParameterValueProvider val3 = new ParameterValueProvider(val); ParameterValueProvider val4 = new ParameterValueProvider(val2); FilterNumericRuleEvaluator val5 = new FilterNumericEquals(); ElementParameterFilter[] array = (ElementParameterFilter[])new ElementParameterFilter[VALID_CURRENT_LOD_VALUES.Length]; for (int i = 0; i < VALID_CURRENT_LOD_VALUES.Length; i++) { FilterIntegerRule val6 = new FilterIntegerRule(val3, val5, VALID_CURRENT_LOD_VALUES[i]); array[i] = new ElementParameterFilter(val6, true); } curLODfilter = new LogicalAndFilter((IList <ElementFilter>)array); ElementParameterFilter[] array2 = (ElementParameterFilter[])new ElementParameterFilter[VALID_TARGET_LOD_VALUES.Length]; for (int j = 0; j < VALID_TARGET_LOD_VALUES.Length; j++) { FilterIntegerRule val7 = new FilterIntegerRule(val4, val5, VALID_TARGET_LOD_VALUES[j]); array2[j] = new ElementParameterFilter(val7, true); } tarLODfilter = new LogicalAndFilter((IList <ElementFilter>)array2); return(true); }
protected void RegisterInputParams(GH_InputParamManager manager, MethodInfo methodInfo) { var elementFilterClasses = new List <Type>(); foreach (var parameter in methodInfo.GetParameters()) { if (parameter.Position < 2) { continue; } if (parameter.IsOut || parameter.ParameterType.IsByRef) { throw new NotImplementedException(); } var parameterType = GetParameterType(parameter, out var access, out var optional); var nickname = parameter.Name.First().ToString().ToUpperInvariant(); var name = nickname + parameter.Name.Substring(1); foreach (var nickNameAttribte in parameter.GetCustomAttributes(typeof(NickNameAttribute), false).Cast <NickNameAttribute>()) { nickname = nickNameAttribte.NickName; } var description = string.Empty; foreach (var descriptionAttribute in parameter.GetCustomAttributes(typeof(DescriptionAttribute), false).Cast <DescriptionAttribute>()) { description = (description.Length > 0) ? $"{description}\r\n{descriptionAttribute.Description}" : descriptionAttribute.Description; } var param = manager[manager.AddParameter(CreateParam(parameterType), name, nickname, description, access)]; param.Optional = optional; if (parameterType.IsEnum && param is Param_Integer integerParam) { foreach (var e in Enum.GetValues(parameterType)) { integerParam.AddNamedValue(Enum.GetName(parameterType, e), (int)e); } } else if (parameterType == typeof(Autodesk.Revit.DB.Element) || parameterType.IsSubclassOf(typeof(Autodesk.Revit.DB.Element))) { elementFilterClasses.Add(parameterType); } else if (parameterType == typeof(Autodesk.Revit.DB.Category)) { elementFilterClasses.Add(typeof(Autodesk.Revit.DB.Element)); } } if (elementFilterClasses.Count > 0 && !elementFilterClasses.Contains(typeof(Autodesk.Revit.DB.Element))) { elementFilter = (elementFilterClasses.Count == 1) ? (ElementFilter) new Autodesk.Revit.DB.ElementClassFilter(elementFilterClasses[0]) : (ElementFilter) new Autodesk.Revit.DB.LogicalOrFilter(elementFilterClasses.Select(x => new Autodesk.Revit.DB.ElementClassFilter(x)).ToArray()); } }
public TerrUpdater(ElementFilter filter, ChangeType chtype) { TriggerPairs = new List <TriggerPair>() { new TriggerPair(filter, chtype) }; SharedParameterSettings = new List <SharedParameterSettings>(); SelfInvoked = false; }
public ActionResult Near(long id, string filterSource) { var element = ServiceContext.ElementService.GetByIdExtended(id); ElementFilter filter = SerializationHelper.DeSerializeJSON <ElementFilter>(filterSource); filter.LatitudeBase = element.Latitude.ToString().Replace(",", "."); filter.LongitudeBase = element.Longitude.ToString().Replace(",", "."); filter.Radius = "1";//Próximo a 1 km do ponto selecionado return(RedirectToAction("List", new { filterSource = SerializationHelper.SerializeJSON <ElementFilter>(filter) })); }
protected void AddFilter(ElementFilter filter, bool next) { if (next) { this.SetNext(filter); } else { this.SetChild(filter); } }
public override void ConfigureBuildingTemplate(GameObject go, Tag prefab_tag) { go.GetComponent <KPrefabID>().AddTag(RoomConstraints.ConstraintTags.IndustrialMachinery, false); go.AddOrGet <Structure>(); ElementFilter elementFilter = go.AddOrGet <ElementFilter>(); elementFilter.portInfo = secondaryPort; Filterable filterable = go.AddOrGet <Filterable>(); filterable.filterElementState = Filterable.ElementState.Gas; }
public ActionResult List(string filterSource, int page = 1) { Session["LastFilter"] = filterSource; page--; int recordCount = 0; ElementFilter filter = SerializationHelper.DeSerializeJSON <ElementFilter>(filterSource); var result = ServiceContext.ElementService.List(out recordCount, filter, null, SiteContext.MaximumRows * page, SiteContext.MaximumRows);// Context.ElementService.List(out recordCount, filter, null, 1 * page, 1); ViewBag.FilterSource = filterSource; ViewBag.RecordCount = recordCount; return(View(result)); }
public ActionResult Search(ElementFilter elementFilter, int page = 1, bool windowMode = false) { page--; windowMode = true; int recordCount = 0; //elementFilter.ZeroAll(); var result = ServiceContext.ElementService.List(out recordCount, elementFilter, null, SiteContext.MaximumRows * page, SiteContext.MaximumRows); ViewBag.RecordCount = recordCount; ViewBag.WindowMode = windowMode; return(View(result)); }
/// <summary> /// Gets element filter for specific views. /// </summary> /// <param name="exporter">The ExporterIFC object.</param> /// <returns>The element filter.</returns> private static ElementFilter GetViewSpecificTypesFilter(ExporterIFC exporter) { ElementFilter ownerViewFilter = GetOwnerViewFilter(exporter); List<Type> viewSpecificTypes = new List<Type>(); viewSpecificTypes.Add(typeof(TextNote)); viewSpecificTypes.Add(typeof(FilledRegion)); ElementMulticlassFilter classFilter = new ElementMulticlassFilter(viewSpecificTypes); LogicalAndFilter viewSpecificTypesFilter = new LogicalAndFilter(ownerViewFilter, classFilter); return viewSpecificTypesFilter; }
internal void SetNext(ElementFilter next) { if (this.CurrentFilter.IsNull()) { this.FilterList.Add(next); } else { this.CurrentFilter.Next = next; } this.CurrentFilter = next; }
internal void SetChild(ElementFilter child) { if (this.CurrentFilter.IsNull()) { this.FilterList.Add(child); } else { this.CurrentFilter.Child = child; } this.CurrentFilter = child; }
public IList <ElementExtended> List(out int recordCount, ElementFilter filter, string sortType = null, int startRowIndex = -1, int maximumRows = -1, bool loadAttributes = false) { List <object> parameters = new List <object>(); string sortExp = "NAME"; string sortDirection = "ASC"; SqlParameter recordCountParameter = new SqlParameter("RecordCount", 0); recordCountParameter.Direction = System.Data.ParameterDirection.Output; StringBuilder sql = new StringBuilder(); parameters.Add(new SqlParameter("Filter", SerializationHelper.SerializeAsDocument <ElementFilter>(filter).OuterXml)); parameters.Add(new SqlParameter("IDCulture", filter.IDCulture)); parameters.Add(new SqlParameter("StartRowIndex", startRowIndex)); parameters.Add(new SqlParameter("MaximumRows", maximumRows)); parameters.Add(recordCountParameter); if (sortType != null) { var sort = sortType.Split(' '); if (sort.Length == 1) { sortExp = sort[0]; } if (sort.Length == 2) { sortExp = sort[0]; sortDirection = sort[1]; } } sortExp = sortExp.Trim().ToUpper(); sortDirection = sortDirection.Trim().ToUpper(); parameters.Add(new SqlParameter("SortExpr", sortExp)); parameters.Add(new SqlParameter("SortDir", sortDirection)); using (var context = new ImobeNetContext()) { sql.AppendLine("exec pElement_GetByDistance @Filter, @IDCulture, @StartRowIndex, @MaximumRows, @SortExpr, @SortDir, @RecordCount out"); var result = context.Database.SqlQuery <Model.ElementExtended>(sql.ToString(), parameters.ToArray()).ToList(); if (loadAttributes) { foreach (var item in result) { item.BasicAttributes = ServiceContext.AttributeService.List("BASIC", item.IDElement.Value); item.StructureAttributes = ServiceContext.AttributeService.List("IE", item.IDElement.Value); } } recordCount = Convert.ToInt32(recordCountParameter.Value); return(result); } }
public IHttpActionResult ListElement(ElementFilter filter) { int recordCount = 0; int maximumRows = (filter.TotalRecodsPerPage == 0) ? SiteContext.MaximumRows : filter.TotalRecodsPerPage; if (filter.UseInternalAuth) { filter.IDCustomer = base.GetAuthCustomer().IDCustomer.Value.ToString(); } var result = ServiceContext.ElementService.List(out recordCount, filter, filter.OrderBy, maximumRows * filter.PageIndex, maximumRows); if (filter.GroupIn == 0) { return(Ok(new { RecordCount = recordCount, Records = result })); } else { List <IEnumerable <ElementExtended> > resultAgregated = new List <IEnumerable <ElementExtended> >(); if (result != null && result.Count() > 0) { int totalPages = (int)(result.Count() / filter.GroupIn); if (result.Count() % filter.GroupIn > 0) { totalPages++; } for (int i = 0; i < totalPages; i++) { resultAgregated.Add(result.Skip(i * filter.GroupIn).Take(filter.GroupIn)); } } return(Ok(new { RecordCount = recordCount, Records = resultAgregated })); } }
private bool ShowInUtilityOverlay(SimViewMode mode, object data) { bool result = false; ElementFilter elementFilter = (ElementFilter)data; switch (elementFilter.portInfo.conduitType) { case ConduitType.Gas: result = (mode == SimViewMode.GasVentMap); break; case ConduitType.Liquid: result = (mode == SimViewMode.LiquidVentMap); break; } return(result); }
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; List <string> categories = new List <string>(); categories.Add("Floors"); categories.Add("Ceilings"); ElementFilter filter = Library.ElementUtils.FiltersElementByCategory(doc, categories); IList <Element> elems = new FilteredElementCollector(doc).WhereElementIsNotElementType().WherePasses(filter) .ToElements(); MessageBox.Show($"Total Ceilings-Floors:{elems.Count}"); return(Result.Succeeded); }
private bool ShowInUtilityOverlay(HashedString mode, object data) { bool result = false; ElementFilter elementFilter = (ElementFilter)data; switch (elementFilter.portInfo.conduitType) { case ConduitType.Gas: result = OverlayModes.GasConduits.ID.Equals(mode); break; case ConduitType.Liquid: result = OverlayModes.LiquidConduits.ID.Equals(mode); break; } return(result); }
public JsonResult MapItem(string filterSource) { Session["LastFilter"] = filterSource; int recordCount = 0; ElementFilter filter = SerializationHelper.DeSerializeJSON <ElementFilter>(filterSource); var result = from r in ServiceContext.ElementService.List(out recordCount, filter, null, 0, SiteContext.MaximumRows) select new { IDElement = r.IDElement.Value, Title = String.Format("{0}-{1}", r.IDElement.Value, r.Name), Latitude = r.Latitude, Longitude = r.Longitude, Icon = String.Format("{0}{1}", SpongeSolutions.ServicoDireto.Admin.SiteContext.LayoutPath, r.IconPath) }; ViewBag.FilterSource = filterSource; ViewBag.RecordCount = recordCount; return(Json(Response <dynamic> .WrapResponse(result, SpongeSolutions.Core.RestFul.Enums.ResponseStatus.OK), JsonRequestBehavior.AllowGet)); }
public ActionResult Similar(long id, string filterSource) { int recordCount = 0; var element = ServiceContext.ElementService.GetByIdExtended(id); ElementFilter filter = SerializationHelper.DeSerializeJSON <ElementFilter>(filterSource); filter.LatitudeBase = element.Latitude.ToString().Replace(",", "."); filter.LongitudeBase = element.Longitude.ToString().Replace(",", "."); filter.Radius = "1";//Próximo a 1 km do ponto selecionado filter.IDCustomer = (Session["IDCustomer"] == null) ? "0" : Session["IDCustomer"].ToString(); var result = ServiceContext.ElementService.List(out recordCount, filter, null, 0, 10); //Ignorando o selecionado if (result != null && result.Count > 0) { result = result.Where(p => p.IDElement != id).ToList(); } return(View(result)); }
public void RequiredScope() { ElementFilter filter; filter = new ElementFilter("$(Name) : 'Style'"); Assert.AreEqual(ElementAttributeScope.Element, filter.RequiredScope); filter = new ElementFilter("$(Name) : 'Style' Or $(Name) : 'Test'"); Assert.AreEqual(ElementAttributeScope.Element, filter.RequiredScope); filter = new ElementFilter("$(Parent.Name) : 'Style'"); Assert.AreEqual(ElementAttributeScope.Parent, filter.RequiredScope); filter = new ElementFilter("$(Parent.Name) : 'Style' Or $(Name) : 'Style'"); Assert.AreEqual(ElementAttributeScope.Parent, filter.RequiredScope); filter = new ElementFilter("$(Name) : 'Style' Or $(Parent.Name) : 'Style'"); Assert.AreEqual(ElementAttributeScope.Parent, filter.RequiredScope); }
public AttenuationCalculator( Document doc, Settings settings) { _doc = doc; _settings = settings; // Find a 3D view to use for the // ReferenceIntersector constructor. _view3d = new FilteredElementCollector(doc) .OfClass(typeof(View3D)) .Cast <View3D>() .First <View3D>(v => !v.IsTemplate); _wallFilter = new ElementClassFilter( typeof(Wall)); }
public static IList <ElementId> GetDependentElements(this Element element, ElementFilter filter) { try { using (var transaction = new Transaction(element.Document, nameof(GetDependentElements))) { transaction.Start(); var collection = element.Document.Delete(element.Id); if (filter is null) { return(collection?.ToList()); } return(collection?.Where(x => filter.PassesFilter(element.Document, x)).ToList()); } } catch { } return(default);
/***************************************************/ /**** Public methods ****/ /***************************************************/ public static ElementFilter StructuralTypeFilter(this ElementFilter filter, Type bHoMType) { if (bHoMType == typeof(Column)) { return(new LogicalOrFilter(filter, new ElementStructuralTypeFilter(StructuralType.Column))); } else if (bHoMType == typeof(Bracing)) { return(new LogicalOrFilter(filter, new ElementStructuralTypeFilter(StructuralType.Brace))); } else if (bHoMType == typeof(Beam)) { return(new LogicalAndFilter(new List <ElementFilter> { filter, new ElementStructuralTypeFilter(StructuralType.Brace, true), new ElementStructuralTypeFilter(StructuralType.Column, true), new ElementStructuralTypeFilter(StructuralType.Footing, true) })); } else { return(filter); } }
/// <summary> /// Find Elements Intersect By Ray /// </summary> /// <param name="element"></param> /// <param name="categories"></param> /// <param name="direction"></param> /// <returns></returns> public static Autodesk.Revit.DB.XYZ RayIntersect(this Autodesk.Revit.DB.Element element, List <string> categories, XYZ direction) { // Find a 3D view to use for the ReferenceIntersector constructor FilteredElementCollector collector = new FilteredElementCollector(element.Document); Func <View3D, bool> isNotTemplate = v3 => !(v3.IsTemplate); View3D view3D = collector.OfClass(typeof(View3D)).Cast <View3D>().First <View3D>(isNotTemplate); // Use the center of the skylight bounding box as the start point. BoundingBoxXYZ box = element.get_BoundingBox(view3D); XYZ center = box.Min.Add(box.Max).Multiply(0.5); // Project in the negative Z direction down to the ceiling. ElementFilter elementFilter = element.Document.FiltersElementByCategory(categories); ReferenceIntersector refIntersector = new ReferenceIntersector(elementFilter, FindReferenceTarget.Face, view3D); refIntersector.FindReferencesInRevitLinks = true; ReferenceWithContext referenceWithContext = refIntersector.FindNearest(center, direction); Reference reference = referenceWithContext?.GetReference(); return(reference?.GlobalPoint); }
/// <summary> /// Initialize filter data with existing view filters /// </summary> void InitializeFilterData() { // Get all existing filters ICollection <ParameterFilterElement> filters = FiltersUtil.GetViewFilters(m_doc); foreach (ParameterFilterElement filter in filters) { // Get all data of the current filter and create my FilterData ICollection <ElementId> catIds = filter.GetCategories(); // Get the ElementFilter representing the set of FilterRules. ElementFilter elemFilter = filter.GetElementFilter(); // Check that the ElementFilter represents a conjunction of ElementFilters. // We will then check that each child ElementFilter contains just one FilterRule. IList <FilterRule> filterRules = FiltersUtil.GetConjunctionOfFilterRulesFromElementFilter(elemFilter); int numFilterRules = filterRules.Count; if (0 == numFilterRules) { return; // Error } // Create filter rule data now List <FilterRuleBuilder> ruleDataSet = new List <FilterRuleBuilder>(); foreach (FilterRule filterRule in filterRules) { ElementId paramId = filterRule.GetRuleParameter(); int parameterIdAsInt = paramId.IntegerValue; BuiltInParameter bip = (BuiltInParameter)parameterIdAsInt; FilterRuleBuilder ruleData = FiltersUtil.CreateFilterRuleBuilder(bip, filterRule); ruleDataSet.Add(ruleData); } // // Create Filter data FilterData filterData = new FilterData(m_doc, catIds, ruleDataSet); m_dictFilters.Add(filter.Name, filterData); // // also add to control filtersListBox.Items.Add(filter.Name); } }
private void InitializeStatusItems() { if (filterStatusItem == null) { filterStatusItem = new StatusItem("Filter", "BUILDING", string.Empty, StatusItem.IconType.Info, NotificationType.Neutral, false, OverlayModes.LiquidConduits.ID, true, 129022); filterStatusItem.resolveStringCallback = delegate(string str, object data) { ElementFilter elementFilter = (ElementFilter)data; if (elementFilter.filteredElem == SimHashes.Void) { str = string.Format(BUILDINGS.PREFABS.GASFILTER.STATUS_ITEM, BUILDINGS.PREFABS.GASFILTER.ELEMENT_NOT_SPECIFIED); } else { Element element = ElementLoader.FindElementByHash(elementFilter.filteredElem); str = string.Format(BUILDINGS.PREFABS.GASFILTER.STATUS_ITEM, element.name); } return(str); }; filterStatusItem.conditionalOverlayCallback = ShowInUtilityOverlay; } }
private void ApplyDirectionChangeToBlocks(List<IHTMLElement> elements, string direction, ElementFilter filter) { using (IUndoUnit undo = CreateUndoUnit()) { foreach (IHTMLElement element in elements) { element.removeAttribute("dir", 0); if (!filter(element)) { element.setAttribute("dir", direction, 0); // If the element is empty, MSHTML won't render the cursor on the correct side of the canvas // until the the users starts typing. We can force the empty element to render correctly by // setting the inflateBlock property. if (String.IsNullOrEmpty(element.innerHTML)) { ((IHTMLElement3)element).inflateBlock = true; } } } undo.Commit(); } }
private void ApplyDirectionChange(string direction, ElementFilter filter) { using (IUndoUnit undo = CreateUndoUnit()) { MarkupRange bounds = FindBoundaries(Selection.SelectedMarkupRange); List<IHTMLElement> blocks = GetBlockElements(bounds); List<MarkupRange> unwrappedContentRanges = GetUnwrappedContentRanges(blocks, bounds); foreach (MarkupRange contentRange in unwrappedContentRanges) { blocks.Add(HtmlStyleHelper.WrapRangeInElement(MarkupServices, contentRange, this.DefaultBlockElement.TagId)); } if (blocks.Count == 0) { // If there are no block elements at all, create one. IHTMLElement newElement = HtmlStyleHelper.WrapRangeInElement(MarkupServices, bounds, this.DefaultBlockElement.TagId); blocks.Add(newElement); // Make sure the selection is inside of it. MarkupRange selection = Selection.SelectedMarkupRange.Clone(); selection.MoveToElement(newElement, false); selection.ToTextRange().select(); } ApplyDirectionChangeToBlocks(blocks, direction, filter); undo.Commit(); } }
private bool SelectionHasDir(ElementFilter filter) { if (Selection != null) { try { MarkupRange bounds = FindBoundaries(Selection.SelectedMarkupRange); // All block elements can have the language direction attribute applied to them. List<IHTMLElement> blocks = GetBlockElements(bounds); List<MarkupRange> unwrappedContentRanges = GetUnwrappedContentRanges(blocks, bounds); if (unwrappedContentRanges.Count > 0 || blocks.Count == 0) { // Unwrapped content ranges inherit their language direction from their parent block element. blocks.Add(bounds.ParentBlockElement()); } // Return true if all the selected content has the same direction. return blocks.TrueForAll(e => filter(e)); } catch (Exception e) { //Eat error that seems to commonly occur when the selection is in an invalid state //(like when it is stale from a previously loaded document!). If this error message //is displayed, we need to figure out why the selection object is invalid. Debug.Fail("Selection object is in an invalid state. Figure out why!", e.ToString()); } } return false; }