Exemple #1
0
        public LayerGroup GetLayerGroupUnfiltered(IPersistEntity ent)
        {
            var suitableroots = _doc.GetConceptRoots(ent.ExpressType);
            var ret           = 1; // does not apply

            //Debug.WriteLine("Entity label: #" + ent.EntityLabel + " Name:" + ent + " suitableroots: " + suitableroots.Count);
            foreach (var validRoot in suitableroots)
            {
                //Debug.WriteLine(validRoot.uuid  + @" " + validRoot.name);
                foreach (var cpt in validRoot.Concepts)
                {
                    switch (cpt.Test(ent, Concept.ConceptTestMode.ThroughRequirementRequirements))
                    {
                    case ConceptTestResult.Fail:
                        return(LayerGroup.Red);     // any fail makes it a fail

                    case ConceptTestResult.Pass:
                        ret = Math.Max(ret, (int)LayerGroup.Green);      // if there is a pass then it does apply
                        break;

                    case ConceptTestResult.Warning:
                        ret = Math.Max(ret, (int)LayerGroup.Amber);     // if there is a pass then it does apply
                        break;
                    }
                }
            }
            return((LayerGroup)ret); // otherwise it does not
        }
Exemple #2
0
        internal void AssignEntity(IPersistEntity parent, IPersistEntity entity, ReferenceContext context)
        {
            if (context.MetaProperty != null && context.MetaProperty.IsDerived)
            {
                Log.WriteLine("It wasn't possible to add entity {0} as a {1} to parent {2} because it is a derived value",
                              entity.ExpressType.ExpressName, context.Segment, parent.ExpressType.ExpressName);
                return;
            }

            var index = context.Index == null ? null : new[] { context.Index };

            //inverse property
            if (context.MetaProperty != null && context.MetaProperty.IsInverse)
            {
                var remotePropName = context.MetaProperty.InverseAttributeProperty.RemoteProperty;
                var entityType     = entity.ExpressType;
                var remoteProp     = GetProperty(entityType, remotePropName);
                //it is enumerable inverse
                if (remoteProp.EnumerableType != null)
                {
                    var list = remoteProp.PropertyInfo.GetValue(entity, index) as IList;
                    if (list != null)
                    {
                        list.Add(parent);
                        return;
                    }
                }
                //it is a single inverse entity
                else
                {
                    remoteProp.PropertyInfo.SetValue(entity, parent, index);
                    return;
                }
                Log.WriteLine("It wasn't possible to add entity {0} as a {1} to parent {2}",
                              entity.ExpressType.ExpressName, context.Segment, entityType.ExpressName);
                return;
            }
            //explicit property
            var info = context.PropertyInfo;

            if (context.ContextType == ReferenceContextType.EntityList)
            {
                var list = info.GetValue(parent, index) as IList;
                if (list != null)
                {
                    list.Add(entity);
                    return;
                }
            }
            else
            {
                if ((context.MetaProperty != null && context.MetaProperty.IsExplicit) || info.GetSetMethod() != null)
                {
                    info.SetValue(parent, entity, index);
                    return;
                }
            }
            Log.WriteLine("It wasn't possible to add entity {0} as a {1} to parent {2}",
                          entity.ExpressType.ExpressName, context.Segment, parent.ExpressType.ExpressName);
        }
        public IXbimViewModel FindItemBreadthFirst(IPersistEntity entity)
        {
            Queue <IXbimViewModel> queue = new Queue <IXbimViewModel>();

            foreach (var item in HierarchySource.OfType <IXbimViewModel>())
            {
                queue.Enqueue(item);
            }
            IXbimViewModel current = queue.Dequeue();

            while (current != null)
            {
                if (IsMatch(current, entity))
                {
                    return(current);
                }
                foreach (var item in current.Children)
                {
                    queue.Enqueue(item);
                }
                if (!queue.Any())
                {
                    return(null);
                }
                current = queue.Dequeue();
            }
            return(null);
        }
Exemple #4
0
        private object GetPropertyValue(string pathPart, IPersistEntity entity, ExpressType type)
        {
            var propName  = pathPart;
            var ofType    = GetPropertyTypeOf(ref propName);
            var propIndex = GetPropertyIndex(ref propName);
            var pInfo     = GetPropertyInfo(propName, type, propIndex);
            var value     = pInfo.GetValue(entity, propIndex == null ? null : new[] { propIndex });

            if (ofType == null || value == null)
            {
                return(value);
            }

            var vType = value.GetType();

            if (!typeof(IEnumerable).IsAssignableFrom(vType))
            {
                return(ofType.IsAssignableFrom(vType) ? value : null);
            }

            var ofTypeMethod = vType.GetMethod("OfType");

            ofTypeMethod = ofTypeMethod.MakeGenericMethod(ofType);
            return(ofTypeMethod.Invoke(value, null));
        }
Exemple #5
0
        private static void WriteXml(IModel model, string path)
        {
            using (var xml = XmlWriter.Create(path, new XmlWriterSettings {
                Indent = true
            }))
            {
                var writer    = new XbimXmlWriter4(configuration.IFC4Add1);
                var project   = model.Instances.OfType <IfcProject>();
                var products  = model.Instances.OfType <IfcObject>();
                var relations = model.Instances.OfType <IfcRelationship>();

                var all =
                    new IPersistEntity[] {}
                //start from root
                .Concat(project)
                //add all products not referenced in the project tree
                .Concat(products)
                //add all relations which are not inversed
                .Concat(relations)
                //make sure all other objects will get written
                .Concat(model.Instances);

                writer.Write(model, xml, all);
                xml.Close();
            }
        }
        internal bool RemoveReversible(IPersistEntity entity)
        {
            if (_model.IsTransactional && _model.CurrentTransaction == null)
            {
                throw new Exception("Operation out of transaction");
            }
            var    key      = entity.GetType();
            bool   removed  = false;
            Action doAction = () =>
            {
                _internal.Remove(key, entity);
                removed = _collection.Remove(entity.EntityLabel);
                _naturalOrder?.Remove(entity.EntityLabel);
            };
            Action undo = () =>
            {
                _internal.Add(key, entity);
                _collection.Add(entity.EntityLabel, entity);
                _naturalOrder?.Add(entity.EntityLabel);
            };

            if (!_model.IsTransactional)
            {
                doAction();
                return(removed);
            }
            _model.CurrentTransaction.DoReversibleAction(doAction, undo, entity, ChangeType.Deleted, 0);
            return(removed);
        }
Exemple #7
0
        //FillOjbectData,GetPropItem, ReportProperty主要处理关于EXPRESSTYPE的属性
        private void FillObjectData(IPersistEntity _entity, ObservableCollection <PropertyItem> _objectProperties)
        {
            if (_objectProperties.Count > 0)
            {
                return; //don't fill unless empty
            }
            if (_entity == null)
            {
                return;
            }

            //_objectProperties.Add(new PropertyItem { Name = "Label", Value = "#" + _entity.EntityLabel, PropertySetName = "General" });

            var ifcType = _entity.ExpressType;

            _objectProperties.Add(new PropertyItem {
                Name = "Type", Value = ifcType.Type.Name, PropertySetName = "General"
            });

            var ifcObj = _entity as IIfcObject;


            var props = ifcType.Properties.Values;

            foreach (var prop in props)
            {
                ReportProp(_entity, prop, false, _objectProperties);
            }
        }
        /// <summary>
        /// This function will try and release a persistent entity from the model, if the entity is referenced by another entity
        /// it will stay in the model but can only be accessed via other entities,however if the model is saved and then reloaded
        /// the entity will be restored to persisted status
        /// if the the entity is not referenced it will be garbage collected and removed and lost
        /// All entities that are directly referenced by this entity will also be made candidates to be dropped and dropped
        /// inverse references are not pursued
        /// Once dropped an entity cannot be accessed via the instances collection.
        /// Returns a collection of entities that have been dropped
        /// </summary>
        /// <param name="entity">the root entity to drop</param>
        public IEnumerable <IPersistEntity> TryDrop(IPersistEntity entity)
        {
            var dropped = new HashSet <IPersistEntity>();

            TryDrop(entity, dropped);
            return(dropped);
        }
        internal void HandleEntityChange(ChangeType changeType, IPersistEntity entity, int propertyOrder)
        {
            switch (changeType)
            {
            case ChangeType.New:
                if (EntityNew != null)
                {
                    EntityNew(entity);
                }
                break;

            case ChangeType.Deleted:
                if (EntityDeleted != null)
                {
                    EntityDeleted(entity);
                }
                break;

            case ChangeType.Modified:
                if (EntityModified != null)
                {
                    EntityModified(entity, propertyOrder);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException("changeType", changeType, null);
            }
        }
        private static bool IsUserDefinedType(IPersistEntity entity)
        {
            var property = entity.ExpressType.Properties
                           .FirstOrDefault(p => string.Equals(p.Value.Name, "PredefinedType", StringComparison.OrdinalIgnoreCase));

            if (property.Value == null)
            {
                return(false);
            }
            var pInfo = property.Value.PropertyInfo;
            var value = pInfo.GetValue(entity);

            if (value == null)
            {
                return(false);
            }

            var pType = pInfo.PropertyType;

            if (pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                var inner      = Nullable.GetUnderlyingType(pInfo.PropertyType);
                var hasValInfo = pInfo.PropertyType.GetProperty(nameof(Nullable <int> .HasValue));
                if ((bool)hasValInfo.GetValue(value) == false)
                {
                    return(false);
                }

                var valInfo = pInfo.PropertyType.GetProperty(nameof(Nullable <int> .Value));
                value = valInfo.GetValue(value);
                pType = pType.GetGenericArguments()[0];
            }

            return(string.Equals(value.ToString(), "USERDEFINED", StringComparison.OrdinalIgnoreCase));
        }
        private string GetErrIdentityInfo(IPersistEntity entity)
        {
            var xmlRef   = _idMap.FirstOrDefault(kv => kv.Value == entity.EntityLabel).Key;
            var et       = entity.ExpressType;
            var guidProp = et.Properties.FirstOrDefault(p => p.Value.Name == "GlobalId").Value;
            var nameProp = et.Properties.FirstOrDefault(p => p.Value.Name == "Name").Value;

            var identityBuilder = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(xmlRef))
            {
                identityBuilder.AppendFormat("id/ref={0} ", xmlRef);
            }
            if (guidProp != null)
            {
                var guidObj = guidProp.PropertyInfo.GetValue(entity);
                if (guidObj != null && !string.IsNullOrWhiteSpace(guidObj.ToString()))
                {
                    identityBuilder.AppendFormat("guid='{0}' ", guidObj.ToString());
                }
            }
            if (nameProp != null)
            {
                var nameObj = nameProp.PropertyInfo.GetValue(entity);
                if (nameObj != null && !string.IsNullOrWhiteSpace(nameObj.ToString()))
                {
                    identityBuilder.AppendFormat("name='{0}' ", nameObj.ToString());
                }
            }
            return(identityBuilder.ToString().Trim());
        }
Exemple #12
0
        private DataFragment GetAttributes(AttributeRule[] attributeRules, IPersistEntity entity, DataIndicatorLookup dataIndicators, string prefix)
        {
            // 1.  get all values

            // add values at this level
            //
            var fragments = new List <DataFragment>();
            var t1        = ExtractRulesValues(entity, dataIndicators, attributeRules, prefix);

            if (t1 != null)
            {
                fragments.Add(t1);
            }

            // process the rest of the tree
            //
            var t = ProcessRuleTree(entity, dataIndicators, attributeRules, prefix);

            if (t != null)
            {
                fragments.Add(t);
            }


            // 2. combine them and return
            return(DataFragment.Combine(fragments));
        }
        internal static TextHighliter ReportAcadScript(IPersistEntity obj)
        {
            var sb = new TextHighliter();

            if (obj is IIfcClosedShell)
            {
                Report((IIfcClosedShell)obj, sb);
            }
            if (obj is IIfcPolyLoop)
            {
                Report((IIfcPolyLoop)obj, sb);
            }
            if (obj is IIfcSweptDiskSolid)
            {
                Report((IIfcSweptDiskSolid)obj, sb);
            }
            else
            {
                sb.Append("No information", Brushes.Black);
                return(sb);
            }
            sb.Append("3DORBIT", Brushes.Black);
            sb.Append("", Brushes.Black);
            sb.Append("===", Brushes.Black);
            return(sb);
        }
Exemple #14
0
        public void Add <T>(string inverseProperty, IPersistEntity inverseArgument, IEnumerable <T> entities)
            where T : IPersistEntity
        {
            var key = new CacheKey(inverseProperty, inverseArgument, typeof(T));

            _cache.Add(key, entities.Cast <IPersistEntity>());
        }
Exemple #15
0
        private string GetMetaComment(IPersistEntity e)
        {
            var tName = e.ExpressType.ExpressNameUpper;
            var props = e.ExpressType.Properties.Select(kv => kv.Value.Name);

            return($"{tName}=({string.Join(", ", props)})");
        }
Exemple #16
0
 public XbimParserState(IPersistEntity entity, ILogger logger = null)
 {
     _currentInstance = new Part21Entity(entity);
     _processStack.Push(_currentInstance);
     _logger   = logger;
     _metadata = entity.Model.Metadata;
 }
        private void AddReversible(IPersistEntity entity)
        {
            if (_model.IsTransactional && _model.CurrentTransaction == null)
            {
                throw new Exception("Operation out of transaction");
            }
            var    key  = entity.GetType();
            Action undo = () =>
            {
                _internal.Remove(key, entity);
                _collection.Remove(entity.EntityLabel);
                if (_naturalOrder != null)
                {
                    _naturalOrder.Remove(entity.EntityLabel);
                }
            };
            Action doAction = () =>
            {
                _internal.Add(key, entity);
                _collection.Add(entity.EntityLabel, entity);
                if (_naturalOrder != null)
                {
                    _naturalOrder.Add(entity.EntityLabel);
                }
            };

            if (!_model.IsTransactional)
            {
                doAction();
                return;
            }

            _model.CurrentTransaction.DoReversibleAction(doAction, undo, entity, ChangeType.New, 0);
        }
        private void Join(IPersistEntity entity, ReferenceContext context,
                          Stack <IPersistEntity> parents)
        {
            var            temp = new Stack <IPersistEntity>();
            IPersistEntity parent;

            while (parents.Count != 0)
            {
                parent = parents.Pop();
                if (context.ContextType == ReferenceContextType.EntityList)
                {
                    Store.AssignEntity(parent, entity, context);
                    temp.Push(parent);
                    break;
                }

                var e = Store.ResolveContext(context.ParentContext, -1, true);
                Store.AssignEntity(e, entity, context);
                context = context.ParentContext;
                entity  = e;
                temp.Push(e);
            }

            //fill parents with the new stuff
            while (temp.Count != 0)
            {
                parent = temp.Pop();
                parents.Push(parent);
            }
        }
Exemple #19
0
 public ReportResult(Concept cpt, IPersistEntity selectedEntity, ConceptTestResult result, ModelViewExchangeRequirement requirement)
 {
     Concept     = cpt;
     Entity      = selectedEntity;
     TestResult  = result;
     Requirement = requirement;
 }
 public ForwardReference(IPersistEntity entity, ReferenceContext context, TableStore store)
 {
     Store   = store;
     _handle = new XbimInstanceHandle(entity);
     Row     = context.CurrentRow;
     Context = context;
 }
Exemple #21
0
        //FillPropertyData, AddPropertySet, AddProperty主要处理关于propertyset的属性
        private void FillPropertyData(IPersistEntity _entity, ObservableCollection <PropertyItem> _properties)
        {
            if (_properties.Any()) //don't try to fill unless empty
            {
                return;
            }
            //now the property sets for any

            if (_entity is IIfcObject)
            {
                var asIfcObject = (IIfcObject)_entity;
                foreach (
                    var pSet in
                    asIfcObject.IsDefinedBy.Select(
                        relDef => relDef.RelatingPropertyDefinition as IIfcPropertySet)
                    )
                {
                    AddPropertySet(pSet, _properties);
                }
            }
            else if (_entity is IIfcTypeObject)
            {
                var asIfcTypeObject = _entity as IIfcTypeObject;
                if (asIfcTypeObject.HasPropertySets == null)
                {
                    return;
                }
                foreach (var pSet in asIfcTypeObject.HasPropertySets.OfType <IIfcPropertySet>())
                {
                    AddPropertySet(pSet, _properties);
                }
            }
        }
Exemple #22
0
        internal void InternalAdd(IPersistEntity entity)
        {
            if (entity == null)
            {
                return;
            }

            var key = entity.GetType();

            _internal.Add(key, entity);
            try
            {
                _collection.Add(entity.EntityLabel, entity);
                if (_naturalOrder != null)
                {
                    _naturalOrder.Add(entity.EntityLabel);
                }
            }
            catch (Exception ex)
            {
                var exist = _collection[entity.EntityLabel];
                if (entity.ExpressType != exist.ExpressType)
                {
                    _model.Logger?.LogError($"Duplicate entity #{entity.EntityLabel} with different data type ({exist.ExpressType.Name}/{entity.ExpressType.Name})", ex);
                }
                else
                {
                    _model.Logger?.LogWarning($"Duplicate entity #{entity.EntityLabel}", ex);
                }
            }
        }
        private IEnumerable <IPersistEntity> GetXmlOrderedEntities(string schema)
        {
            schema = schema.ToUpperInvariant();
            if (schema == null || !schema.StartsWith("IFC2X"))
            {
                return(Instances);
            }

            var project   = Instances.OfType("IfcProject", true);
            var products  = Instances.OfType("IfcObject", true);
            var relations = Instances.OfType("IfcRelationship", true);

            //create nice deep XML structure if possible
            var all =
                new IPersistEntity[] { }
            //start from root
            .Concat(project)
            //add all products not referenced in the project tree
            .Concat(products)
            //add all relations which are not inversed
            .Concat(relations)
            //make sure all other objects will get written
            .Concat(Instances);

            return(all);
        }
Exemple #24
0
        internal static TextHighliter ReportAcadScript(IPersistEntity obj)
        {
            var sb = new TextHighliter();

            if (obj is IIfcGeometricRepresentationItem cnv)
            {
                Report(cnv, sb);
            }
            else if (obj is IIfcClosedShell)
            {
                Report((IIfcClosedShell)obj, sb);
            }
            else if (obj is IIfcPolyLoop)
            {
                Report((IIfcPolyLoop)obj, sb);
            }
            else if (obj is IIfcSweptDiskSolid)
            {
                Report((IIfcSweptDiskSolid)obj, sb);
            }
            else if (obj is IIfcProductDefinitionShape)
            {
                Report((IIfcProductDefinitionShape)obj, sb);
            }
            else
            {
                sb.Append($"No information for {obj.GetType()}", Brushes.Black);
                return(sb);
            }
            sb.Append("3DORBIT", Brushes.Black);
            sb.Append("", Brushes.Black);
            sb.Append("===", Brushes.Black);
            return(sb);
        }
Exemple #25
0
 public Change(Action doAction, Action undoAction, IPersistEntity entity, ChangeType changeType)
 {
     DoAction   = doAction;
     UndoAction = undoAction;
     Entity     = entity;
     ChangeType = changeType;
 }
Exemple #26
0
        internal IEnumerable <(Type, MethodInfo)> FindGeometryEngineMatch(IPersistEntity entity)
        {
            var methods = typeof(XbimGeometryEngine).GetMethods(BindingFlags.Public | BindingFlags.Instance);

            foreach (var methodInfo in methods)
            {
                var pars = methodInfo.GetParameters().ToArray();

                if (!typeof(IXbimGeometryObject).IsAssignableFrom(methodInfo.ReturnParameter.ParameterType))
                {
                    continue;
                }

                if (pars.Length > 2)
                {
                    continue;
                }

                if (!pars.FirstOrDefault()?.ParameterType.IsInstanceOfType(entity) ?? true)
                {
                    continue;
                }

                var param2nd = pars.Skip(1).FirstOrDefault()?.ParameterType;
                if (null == param2nd || !typeof(ILogger).IsAssignableFrom(param2nd))
                {
                    continue;
                }

                yield return(pars.FirstOrDefault()?.ParameterType, methodInfo);
            }
        }
Exemple #27
0
        private void EntityLabel_KeyDown()
        {
            var            input  = EntityLabel.Text;
            var            re     = new Regex(@"#[ \t]*(\d+)");
            var            m      = re.Match(input);
            IPersistEntity entity = null;

            if (m.Success)
            {
                int isLabel;
                if (!int.TryParse(m.Groups[1].Value, out isLabel))
                {
                    return;
                }
                entity = Model.Instances[isLabel];
            }
            else
            {
                entity = Model.Instances.OfType <IIfcRoot>().FirstOrDefault(x => x.GlobalId == input);
            }

            if (entity != null)
            {
                SelectedItem = entity;
            }
        }
Exemple #28
0
        private int getPropertyValue(IPersistEntity entity, HashSet <ExpressType> type) // labvit: sheetcode
        {
            //int strLength = "ObjectType".Length;
            int retVal = 0;
            ExpressMetaProperty obType = null;

            if (type == null)
            {
                return(0);
            }
            if (type != null && !type.Contains(entity.ExpressType))
            {
                return(0);
            }
            obType = entity.ExpressType.Properties.ToList()[4].Value; // hard coding, it may be realised function below
                                                                      //foreach (var prop in entity.ExpressType.Properties)
                                                                      //    if (string.Compare(prop.Value.Name, "ObjectType", false) == 0)
                                                                      //    {
                                                                      //        obType = prop.Value;
                                                                      //        obType = prop.Value ;
            var ob = obType.PropertyInfo.GetValue(entity);

            if (ob != null)
            {
                retVal = ob.GetHashCode();// GetType().GetProperty("Value").GetValue(ob).GetHashCode();
            }
            //        break;
            //  }

            return(retVal);
        }
Exemple #29
0
        public static WpfMeshGeometry3D GetGeometry(IPersistEntity selection, XbimMatrix3D modelTransform, WpfMaterial mat)
        {
            var tgt = new WpfMeshGeometry3D(mat, mat);

            tgt.BeginUpdate();
            using (var geomstore = selection.Model.GeometryStore)
            {
                using (var geomReader = geomstore.BeginRead())
                {
                    foreach (var shapeInstance in geomReader.ShapeInstancesOfEntity(selection).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded))
                    {
                        IXbimShapeGeometryData shapegeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                        if (shapegeom.Format != (byte)XbimGeometryType.PolyhedronBinary)
                        {
                            continue;
                        }
                        var transform = shapeInstance.Transformation * modelTransform;
                        tgt.Add(
                            shapegeom.ShapeData,
                            shapeInstance.IfcTypeId,
                            shapeInstance.IfcProductLabel,
                            shapeInstance.InstanceLabel,
                            transform,
                            (short)selection.Model.UserDefinedId
                            );
                    }
                }
            }
            tgt.EndUpdate();
            return(tgt);
        }
Exemple #30
0
        //Loads the property data of an entity, if it is not already loaded
        bool IModel.Activate(IPersistEntity entity)
        {
            if (entity.Activated)
            {
                return(true);
            }

            try
            {
                lock (entity)
                {
                    //check again in the lock
                    if (entity.Activated)
                    {
                        return(true);
                    }

                    //activate and set the flag
                    InstanceCache.Activate(entity);
                    FlagSetter.SetActivationFlag(entity, true);
                    return(true);
                }
            }
            catch (Exception e)
            {
                throw new XbimInitializationFailedException(string.Format("Failed to activate #{0}={1}", entity.EntityLabel, entity.ExpressType.ExpressNameUpper), e);
            }
        }