Esempio n. 1
0
 public XbimParserState(IPersistEntity entity, ILogger logger = null)
 {
     _logger          = logger ?? XbimLogging.CreateLogger <EsentModel>();
     _currentInstance = new Part21Entity(entity);
     _processStack.Push(_currentInstance);
     _metadata = entity.Model.Metadata;
 }
Esempio n. 2
0
        public static void Run()
        {
            var log = XbimLogging.CreateLogger <FederationExample>();

            IfcStore.ModelProviderFactory.UseMemoryModelProvider();
            using (var modelA = IfcStore.Open("SampleHouse.ifc"))
                using (var modelB = IfcStore.Open("SampleHouseExtension.ifc"))
                {
                    // just for the purpose of this example
                    modelA.Model.Tag = "Model A";
                    modelB.Model.Tag = "Model B";

                    log.LogInformation("Creating basic federation");
                    var instances = new BasicFederation(new[] { modelA, modelB });

                    log.LogInformation("Starting entity caching and inverse caching to improve performance");
                    using (instances.BeginEntityCaching())
                        using (instances.BeginInverseCaching())
                        {
                            // using IFC4 interfaces will retrieve data from both IFC2x3 and IFC4 models
                            var walls = instances.OfType <IIfcWall>();
                            foreach (var wall in walls)
                            {
                                var pSets = wall.IsDefinedBy
                                            .SelectMany(r => r.RelatingPropertyDefinition.PropertySetDefinitions)
                                            .OfType <IIfcPropertySet>()
                                            .ToList();
                                log.LogInformation("Wall {name} from model '{model}' has {pSetsCount} property sets and {propertyCount} properties",
                                                   wall.Name, wall.Model.Tag, pSets.Count, pSets.Sum(ps => ps.HasProperties.Count));
                            }
                        }
                }
        }
Esempio n. 3
0
        public bool Check(IModel model, string logFile = null)
        {
            // set up error logger handler to get errors from parser
            appender = Logger.Setup(logFile);
            log      = XbimLogging.CreateLogger("Validator");

            return(CheckInternal(model, new Dictionary <int, string>()));
        }
Esempio n. 4
0
        public bool Check(IModel model)
        {
            ILogger log = XbimLogging.CreateLogger <ModelValidator>();

            // check for parser exceptions
            var v = new Validator
            {
                ValidateLevel         = ValidationFlags.All,
                CreateEntityHierarchy = true
            };

            var schemaErrors   = v.Validate(model.Instances);
            var templateErrors = CheckPropertyTemplateTypesAndUnits(model);
            var propertyErrors = CheckPropertyUnits(model);
            var costItemErrors = CheckCostItems(model);

            Errors = schemaErrors
                     .Concat(templateErrors)
                     .Concat(propertyErrors)
                     .Concat(costItemErrors)
                     .ToList();

            foreach (var err in Errors)
            {
                var identity = err.Item.GetType().Name;
                if (err.Item is IPersistEntity entity)
                {
                    identity = $"#{entity.EntityLabel}={entity.ExpressType.ExpressName}";
                }
                var msg = new StringBuilder();
                msg.AppendLine($"{identity} is invalid.");
                var details = new Stack <ValidationResult>(err.Details);
                while (details.Any())
                {
                    var detail = details.Pop();
                    foreach (var d in detail.Details)
                    {
                        details.Push(d);
                    }

                    var report = detail.Message;
                    if (string.IsNullOrWhiteSpace(report))
                    {
                        report = detail.Report();
                    }
                    msg.AppendLine("    " + report);

                    if (detail.IssueType == ValidationFlags.EntityWhereClauses || detail.IssueType == ValidationFlags.TypeWhereClauses)
                    {
                        var source = detail.IssueSource.Split('.')[0].ToLower();
                        msg.AppendLine($"http://www.buildingsmart-tech.org/ifc/IFC4/Add2/html/link/{source}.htm");
                    }
                }
                log.LogError(msg.ToString());
            }

            return(!Errors.Any());
        }
Esempio n. 5
0
 public StepModel(EntityFactoryResolverDelegate factoryResolver, ILogger logger = null, int labelFrom = 0)
 {
     Logger           = logger ?? XbimLogging.CreateLogger <StepModel>();
     _factoryResolver = factoryResolver;
     _instances       = new EntityCollection(this, labelFrom);
     IsTransactional  = true;
     Header           = new StepFileHeader(StepFileHeader.HeaderCreationMode.LeaveEmpty, this);
     ModelFactors     = new XbimModelFactors(Math.PI / 180, 1e-3, 1e-5);
 }
Esempio n. 6
0
        protected XbimP21Parser(ILogger logger)
        {
            Logger = logger ?? XbimLogging.CreateLogger <XbimP21Parser>();
            const int entityApproxCount = 5000;

            _entities           = new Dictionary <long, IPersist>(entityApproxCount);
            _deferredReferences = new List <DeferredReference>(entityApproxCount / 2); //assume 50% deferred
            ErrorCount          = 0;
        }
Esempio n. 7
0
        public FormExample(ILogger logger = null)
        {
            InitializeComponent();
            Logger = logger ?? XbimLogging.CreateLogger <FormExample>();
            IfcStore.ModelProviderFactory.UseHeuristicModelProvider();
            _wpfControl = new WinformsAccessibleControl();
            _wpfControl.SelectionChanged += _wpfControl_SelectionChanged;

            controlHost.Child = _wpfControl;
        }
Esempio n. 8
0
 /// <summary>
 /// Constructs a table and opens it
 /// </summary>
 public EsentEntityCursor(EsentModel model, string database, OpenDatabaseGrbit mode)
     : base(model, database, mode)
 {
     _logger = XbimLogging.CreateLogger <EsentEntityCursor>();;
     Api.JetOpenTable(Sesid, DbId, ifcEntityTableName, null, 0,
                      mode == OpenDatabaseGrbit.ReadOnly ? OpenTableGrbit.ReadOnly :
                      mode == OpenDatabaseGrbit.Exclusive ? OpenTableGrbit.DenyWrite : OpenTableGrbit.None, out Table);
     Api.JetOpenTable(Sesid, DbId, ifcEntityIndexTableName, null, 0,
                      mode == OpenDatabaseGrbit.ReadOnly ? OpenTableGrbit.ReadOnly :
                      mode == OpenDatabaseGrbit.Exclusive ? OpenTableGrbit.DenyWrite : OpenTableGrbit.None, out _indexTable);
     InitColumns();
 }
Esempio n. 9
0
        public StepModel(IEntityFactory entityFactory, int labelFrom)
        {
            Logger = Logger ?? XbimLogging.CreateLogger<StepModel>();
            InitFromEntityFactory(entityFactory);

            _instances = new EntityCollection(this, labelFrom);

            IsTransactional = true;
            ModelFactors = new XbimModelFactors(Math.PI / 180, 1e-3, 1e-5);

            Header = new StepFileHeader(StepFileHeader.HeaderCreationMode.InitWithXbimDefaults, this);
            foreach (var schemasId in EntityFactory.SchemasIds)
                Header.FileSchema.Schemas.Add(schemasId);
        }
Esempio n. 10
0
        public XbimP21Parser(Stream strm, long streamSize, ILogger logger)
            : base(strm)
        {
            Logger = logger ?? XbimLogging.CreateLogger <XbimP21Parser>();
            var entityApproxCount = 5000;

            if (streamSize > 0)
            {
                _streamSize       = streamSize;
                entityApproxCount = Convert.ToInt32(_streamSize / 50); //average 50 bytes per entity.
            }

            _entities           = new Dictionary <long, IPersist>(entityApproxCount);
            _deferredReferences = new List <DeferredReference>(entityApproxCount / 2); //assume 50% deferred
            ErrorCount          = 0;
        }
Esempio n. 11
0
        /// <summary>
        /// Constructor of the reader for IFC2x3 XML. XSD is different for different versions of IFC and there is a major difference
        /// between IFC2x3 and IFC4 to there are two different classes to deal with this.
        /// </summary>x
        /// <param name="getOrCreate">Delegate which will be used to getOrCreate new entities</param>
        /// <param name="finish">Delegate which will be called once the entity is finished (no changes will be made to it)
        /// This is useful for a DB when this is the point when it can be serialized to DB</param>
        /// <param name="metadata">Metadata model used to inspect Express types and their properties</param>
        /// <param name="logger">A Logger</param>
        public XbimXmlReader4(GetOrCreateEntity getOrCreate, FinishEntity finish, ExpressMetaData metadata, ILogger logger)
        {
            if (getOrCreate == null)
            {
                throw new ArgumentNullException("getOrCreate");
            }

            if (finish == null)
            {
                throw new ArgumentNullException("finish");
            }

            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            _getOrCreate = getOrCreate;
            _finish      = finish;
            _metadata    = metadata;
            Logger       = logger ?? XbimLogging.CreateLogger <XbimXmlReader4>();;
        }
Esempio n. 12
0
        public XbimGeometryEngine(ILogger <XbimGeometryEngine> logger)
        {
            // Warn if runtime for Engine is not present, this is not necessary any more as we are net472
            //XbimPrerequisitesValidator.Validate();


            _logger = logger ?? XbimLogging.CreateLogger <XbimGeometryEngine>();

            var    conventions  = new XbimArchitectureConventions();               // understands the process we run under
            string assemblyName = $"{conventions.ModuleName}{conventions.Suffix}"; // Fixed error "simple name should be the same as resolved assembly", eirik 1/15/2021

            _logger.LogDebug("Loading {assemblyName}", assemblyName);
            try
            {
                var ass = Assembly.Load(assemblyName);
                _logger.LogTrace("Loaded {fullName} from {codebase}", ass.GetName().FullName, ass.CodeBase);
                var t   = ass.GetType("Xbim.Geometry.XbimGeometryCreator");
                var obj = Activator.CreateInstance(t);
                _logger.LogTrace("Created Instance of {fullName}", obj.GetType().FullName);
                if (obj == null)
                {
                    throw new Exception("Failed to create Geometry Engine");
                }

                _engine = obj as IXbimGeometryEngine;
                if (_engine == null)
                {
                    throw new Exception("Failed to cast Geometry Engine to IXbimGeometryEngine");
                }

                _logger.LogDebug("XbimGeometryEngine constructed successfully");
            }
            catch (Exception e)
            {
                _logger.LogError(0, e, "Failed to construct XbimGeometryEngine");
                throw new FileLoadException($"Failed to load Xbim.Geometry.Engine.dll{conventions.Suffix}", e);
            }
        }
Esempio n. 13
0
        public XbimP21Scanner(string data, IEnumerable <string> ignoreTypes = null)
        {
            Logger   = XbimLogging.CreateLogger <XbimP21Scanner>();
            _scanner = new Scanner();
            _scanner.SetSource(data, 0);
            _streamSize = data.Length;
            if (ignoreTypes != null)
            {
                SkipTypes = new HashSet <string>(ignoreTypes);
            }
            var entityApproxCount = (int)_streamSize / 50;

            //adjust for skipped entities
            if (SkipTypes.Any())
            {
                //about a 560 entities
                double adjustRatio = 1 - ((double)(SkipTypes.Count)) / 560;
                entityApproxCount = (int)(entityApproxCount * adjustRatio);
            }

            Entities            = new Dictionary <int, IPersist>(entityApproxCount);
            _deferredReferences = new List <DeferredReference>(entityApproxCount / 4); //assume 50% deferred
        }
Esempio n. 14
0
        public XbimP21Scanner(Stream strm, long streamSize, IEnumerable <string> ignoreTypes = null)
        {
            Logger   = XbimLogging.CreateLogger <XbimP21Scanner>();
            _scanner = new Scanner(strm);
            //_scanner = new Scanner(new XbimScanBuffer(strm));
            if (ignoreTypes != null)
            {
                SkipTypes = new HashSet <string>(ignoreTypes);
            }
            var entityApproxCount = 50000;

            if (streamSize > 0)
            {
                _streamSize       = streamSize;
                entityApproxCount = Convert.ToInt32(_streamSize / 50); //average 50 bytes per entity.
            }
            //adjust for skipped entities
            if (SkipTypes.Any())
            {
                //about a 600 entities
                double adjustRatio = 1.0 - (SkipTypes.Count / 600d);
                if (adjustRatio < 0)
                {
                    adjustRatio = 0;
                }
                entityApproxCount = (int)(entityApproxCount * adjustRatio);
            }

            // make it 4 at least
            if (entityApproxCount < 1)
            {
                entityApproxCount = 4;
            }

            Entities            = new Dictionary <int, IPersist>(entityApproxCount);
            _deferredReferences = new List <DeferredReference>(entityApproxCount / 4); //assume 50% deferred
        }
Esempio n. 15
0
 public EsentModel(IEntityFactory factory)
 {
     Logger = XbimLogging.CreateLogger <EsentModel>();
     Init(factory);
 }
Esempio n. 16
0
 private XbimXmlReader4()
 {
     Logger = XbimLogging.CreateLogger <XbimXmlReader4>();;
 }
Esempio n. 17
0
        public bool Check(string file)
        {
            // set up error logger handler to get errors from parser
            var logFile = file + ".log";

            appender = Logger.Setup(logFile);
            log      = XbimLogging.CreateLogger("Validator");


            var ext    = Path.GetExtension(file).ToUpperInvariant().Trim('.');
            var format = "UNKNOWN";

            switch (ext)
            {
            case "IFC":
                format = "STEP21 (*.ifc)";
                break;

            case "IFCXML":
                format = "XML (*.ifcXML)";
                break;

            default:
                break;
            }
            log.LogInformation($"Validating file: {file}");
            log.LogInformation($"File format: {format}");


            try
            {
                // open as an in-memory model (all syntactic errors fill be picked up)
                using (var model = IfcStore.Open(file, null, -1))
                {
                    // header information
                    log.LogInformation($"Schema version: {string.Join(", ", model.Header.SchemaVersion)}");
                    log.LogInformation($"Model View Definitions: {string.Join(", ", model.Header.FileDescription.Description)}");

                    // STEP21 syntactic errors will be reported in the log already
                    if (appender.Errors.Any())
                    {
                        // do not proceed because the data is incomplete
                        return(false);
                    }

                    log.LogInformation($"Number of entities: {model.Instances.Count}");
                    LogEntityHistogram(model);

                    var idMap = new Dictionary <int, string>();
                    if (file.ToLower().EndsWith(".ifcxml"))
                    {
                        using (var stream = File.OpenRead(file))
                        {
                            idMap = GetXmlEntityMap(stream, model);
                        }
                    }

                    CheckInternal(model, idMap);
                }
            }
            // XML syntactic errors will be fired as an exception
            catch (XbimParserException pe)
            {
                log.LogError($"Parser failure: {pe.Message}.");
                return(false);
            }
            catch (Exception ge)
            {
                log.LogError($"General failure: {ge.Message}.", ge);
                return(false);
            }

            return(!Errors.Any() && !Warnings.Any());
        }
Esempio n. 18
0
 /// <summary>
 /// Only inherited models can call parameter-less constructor and it is their responsibility to
 /// call Init() as the very first thing.
 /// </summary>
 internal EsentModel()
 {
     Logger = XbimLogging.CreateLogger <EsentModel>();
 }
Esempio n. 19
0
 public GreyscaleStyler(ILogger logger = null)
 {
     Logger = logger ?? XbimLogging.CreateLogger <RandomColorStyler>();
 }
Esempio n. 20
0
 public StepModel(IEntityFactory entityFactory, ILogger logger = null, int labelFrom = 0) : this(entityFactory, labelFrom)
 {
     Logger = logger ?? XbimLogging.CreateLogger <StepModel>();
 }
 internal static ILogger CreateLogger <T>()
 {
     return(XbimLogging.CreateLogger <T>());
 }
Esempio n. 22
0
 public SurfaceLayerStyler(ILogger logger = null)
 {
     Logger = logger ?? XbimLogging.CreateLogger <SurfaceLayerStyler>();
 }
Esempio n. 23
0
        private void Validate_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog
            {
                CheckFileExists  = true,
                CheckPathExists  = true,
                Multiselect      = false,
                Filter           = "IFC File|*.ifc|IFC XML File|*.ifcxml",
                FilterIndex      = 0,
                Title            = "Select IFC model file for validation",
                FileName         = App.Settings.LastModel,
                InitialDirectory = Path.GetDirectoryName(App.Settings.LastModel)
            };

            if (dlg.ShowDialog() != true)
            {
                return;
            }

            App.Settings.LastModel = dlg.FileName;
            var fileName = dlg.FileName;
            var bcfPath  = Path.ChangeExtension(fileName, ".bcf");

            XbimSchemaVersion schema;

            using (var temp = File.OpenRead(fileName))
            {
                schema = MemoryModel.GetStepFileXbimSchemaVersion(temp);
            }

            var mvd = GetMvd(true, schema);

            var logger = XbimLogging.CreateLogger("MvdValidator");

            using (var ifcStream = File.OpenRead(fileName))
                using (var model = MemoryModel.OpenReadStep21(ifcStream, logger, null, ignoreTypes, false, false))
                {
                    var results = MvdValidator
                                  .ValidateModel(mvd, model)
                                  .ToList();
                    if (results.All(r => r.Concept == null && r.Result == ConceptTestResult.DoesNotApply))
                    {
                        MessageBox.Show("No applicable entities in the file", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    var failed  = results.Where(r => r.Result == ConceptTestResult.Fail).GroupBy(r => r.Entity).ToList();
                    var passed  = results.Where(r => r.Result == ConceptTestResult.Pass).GroupBy(r => r.Entity).ToList();
                    var skipped = results.Where(r => r.Result == ConceptTestResult.DoesNotApply).GroupBy(r => r.Entity).ToList();

                    var bcf = new BCFArchive();

                    // store reports as documents
                    bcf.Documents.Add(WriteResults("failed.csv", failed.SelectMany(g => g)));
                    bcf.Documents.Add(WriteResults("passed.csv", passed.SelectMany(g => g)));
                    bcf.Documents.Add(WriteResults("skipped.csv", skipped.SelectMany(g => g)));

                    // store actual MVD as a document
                    var mvdStream = new MemoryStream();
                    mvd.Serialize(mvdStream);
                    bcf.Documents.Add(new DocumentFile {
                        Name = "validation.mvdXML", Stream = mvdStream
                    });

                    // create topics
                    var failedConcepts = results.Where(r => r.Result == ConceptTestResult.Fail).GroupBy(r => r.Concept.name).ToList();
                    var actor          =
                        ContextSelector.Context.OfType <Actor>().FirstOrDefault()?.Name ??
                        Actors.FirstOrDefault()?.Name ??
                        "*****@*****.**";
                    foreach (var concept in failedConcepts)
                    {
                        var issueId        = Guid.NewGuid();
                        var viewpointId    = Guid.NewGuid();
                        var defViewpointId = Guid.NewGuid();
                        var components     = concept.Select(c => c.Entity).OfType <IIfcRoot>().Select(e => new Component
                        {
                            IfcGuid           = e.GlobalId,
                            AuthoringToolId   = e.OwnerHistory?.OwningApplication?.ApplicationIdentifier,
                            OriginatingSystem = e.EntityLabel.ToString(),
                        }).ToList();

                        var issue = new TopicFolder
                        {
                            Id     = issueId,
                            Markup = new Markup
                            {
                                Header = new List <HeaderFile> {
                                    new HeaderFile {
                                        isExternal = true,
                                        Filename   = Path.GetFileName(fileName),
                                        IfcProject = model.Instances.FirstOrDefault <IIfcProject>()?.GlobalId
                                    }
                                },
                                Topic = new Topic
                                {
                                    CreationDate      = DateTime.Now,
                                    Guid              = issueId.ToString(),
                                    Title             = $"Failed validation of {concept.Key}",
                                    Description       = $"This is automatically generater error report for DSS. This topic refers to all entities which should have {concept.Key} but it wasn't found.",
                                    DocumentReference = new List <TopicDocumentReference> {
                                        new TopicDocumentReference {
                                            isExternal         = false,
                                            ReferencedDocument = "../Documents/failed.csv"
                                        },
                                        new TopicDocumentReference {
                                            isExternal         = false,
                                            ReferencedDocument = "../Documents/validation.mvdXML"
                                        }
                                    },
                                    CreationAuthor = actor
                                },
                                Comment = new List <Comment> {
                                    new Comment {
                                        Date      = DateTime.Now,
                                        Author    = actor,
                                        Comment1  = $"Failed validation of {concept.Key}",
                                        Viewpoint = new CommentViewpoint {
                                            Guid = viewpointId.ToString()
                                        }
                                    }
                                },
                                Viewpoints = new List <ViewPoint> {
                                    new ViewPoint {
                                        Index     = 0,
                                        Guid      = defViewpointId.ToString(),
                                        Viewpoint = "viewpoint.bcfv"
                                    },
                                    new ViewPoint {
                                        Index     = 1,
                                        Guid      = viewpointId.ToString(),
                                        Viewpoint = $"{viewpointId.ToString()}.bcfv"
                                    }
                                }
                            },
                            ViewPoints = new List <VisualizationInfo> {
                                new VisualizationInfo {
                                    Guid       = defViewpointId.ToString(),
                                    Components = new Components {
                                        ViewSetupHints = new ViewSetupHints {
                                            OpeningsVisible = false, SpaceBoundariesVisible = false, SpacesVisible = false
                                        },
                                        Selection = concept.Select(c => c.Entity).OfType <IIfcRoot>().Select(e => new Component {
                                            IfcGuid           = e.GlobalId,
                                            AuthoringToolId   = e.OwnerHistory?.OwningApplication?.ApplicationIdentifier,
                                            OriginatingSystem = e.EntityLabel.ToString(),
                                        }).ToList(),
                                        Visibility = new ComponentVisibility {
                                            DefaultVisibility = true, Exceptions = new List <Component>()
                                        },
                                        Coloring = new List <ComponentColoringColor> {
                                            new ComponentColoringColor {
                                                Color     = "FF00FF00",
                                                Component = components
                                            }
                                        }
                                    },
                                },
                                new VisualizationInfo {
                                    Guid       = viewpointId.ToString(),
                                    Components = new Components {
                                        ViewSetupHints = new ViewSetupHints {
                                            OpeningsVisible = false, SpaceBoundariesVisible = false, SpacesVisible = false
                                        },
                                        Selection  = components,
                                        Visibility = new ComponentVisibility {
                                            DefaultVisibility = false, Exceptions = new List <Component>()
                                        }
                                    },
                                }
                            }
                        };

                        bcf.Topics.Add(issue);
                    }

                    using (var s = File.Create(bcfPath))
                    {
                        bcf.Serialize(s);
                    }

                    if (!failed.Any())
                    {
                        MessageBox.Show($"All {passed.Count} applicable entities are valid. {skipped.Count} entities not applicable.  Reports are saved in '{bcfPath}'",
                                        "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageBox.Show($"{failed.Count} applicable entities are invalid. {skipped.Count} entities not applicable. Reports are saved in '{bcfPath}'",
                                        "Invalid entities", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
        }
 static XbimCustomAssemblyResolver()
 {
     _logger = XbimLogging.CreateLogger <XbimCustomAssemblyResolver>();
 }
Esempio n. 25
0
 public BoundingBoxStyler(ILogger logger = null)
 {
     Logger = logger ?? XbimLogging.CreateLogger <BoundingBoxStyler>();
 }
 public CriticalityStyler(ILogger logger = null)
 {
     Logger = logger ?? XbimLogging.CreateLogger <RandomColorStyler>();
 }
Esempio n. 27
0
 public Scanner(ILogger logger)
 {
     Logger = logger ?? XbimLogging.CreateLogger <Scanner>();
 }