Beispiel #1
0
        /// <summary>
        /// Check if the document information is already within the model
        /// </summary>
        /// <param name="row">COBieDocumentRow data</param>
        /// <returns>bool</returns>
        private bool CheckIfExistOnMerge(COBieDocumentRow row)
        {
            if (XBimContext.IsMerge)
            {
                if (ValidateString(row.Name)) //we have a primary key to check
                {
                    IfcRoot ifcRoot = GetObjectRelationship(row);
                    if (ifcRoot != null)
                    {
                        IfcRelAssociatesDocument ifcRelAssociatesDocument = Model.Instances.Where <IfcRelAssociatesDocument>(di => di.RelatedObjects.Contains(ifcRoot)).FirstOrDefault();
                        if (ifcRelAssociatesDocument != null)
                        {
                            string testName = row.Name.ToLower().Trim();
                            if ((ifcRelAssociatesDocument.RelatingDocument is IfcDocumentInformation) &&
                                ((ifcRelAssociatesDocument.RelatingDocument as IfcDocumentInformation).Name.ToString().ToLower().Trim() == testName)
                                )
                            {
#if DEBUG
                                Console.WriteLine("{0} : with document {1} attached to {2} exists so skip on merge", ifcRelAssociatesDocument.GetType().Name, row.Name, ifcRoot.Name);
#endif
                                return(true); //we have it so no need to create
                            }
                        }
                    }
                }
            }
            return(false);
        }
Beispiel #2
0
        /// <summary>
        /// Get the related object information for the document
        /// </summary>
        /// <param name="ifcRelAssociatesDocument">IfcRelAssociatesDocument object</param>
        /// <returns>RelatedObjectInformation structure</returns>
        private RelatedObjectInformation GetRelatedObjectInformation(IfcRelAssociatesDocument ifcRelAssociatesDocument)
        {
            RelatedObjectInformation objectInfo = new RelatedObjectInformation {
                SheetName = DEFAULT_STRING, Name = DEFAULT_STRING, ExtIdentifier = DEFAULT_STRING, ExtObject = DEFAULT_STRING, CreatedBy = DEFAULT_STRING, CreatedOn = DEFAULT_STRING, ExtSystem = DEFAULT_STRING
            };

            if (ifcRelAssociatesDocument != null)
            {
                IfcRoot relatedObject = ifcRelAssociatesDocument.RelatedObjects.FirstOrDefault();
                if (relatedObject != null)
                {
                    string value = GetSheetByObjectType(relatedObject.GetType());

                    if (!string.IsNullOrEmpty(value))
                    {
                        objectInfo.SheetName = value;
                    }
                    value = relatedObject.Name.ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        objectInfo.Name = value;
                    }
                    objectInfo.ExtObject     = relatedObject.GetType().Name;
                    objectInfo.ExtIdentifier = ifcRelAssociatesDocument.GlobalId;
                    objectInfo.ExtSystem     = GetExternalSystem(ifcRelAssociatesDocument.OwnerHistory);

                    objectInfo.CreatedBy = GetTelecomEmailAddress(ifcRelAssociatesDocument.OwnerHistory);
                    objectInfo.CreatedOn = GetCreatedOnDateAsFmtString(ifcRelAssociatesDocument.OwnerHistory);
                }
            }
            return(objectInfo);
        }
Beispiel #3
0
		internal static void GenerateData(STPModelData md, IfcBuilding building,bool assembly)
		{
			IfcDocumentReference documentReference = new IfcDocumentReference(md, "", "MyReinforcementCode", "MyCodeISO3766", "", null);
			IfcRelAssociatesDocument associatesDocument = new IfcRelAssociatesDocument(md.Project, documentReference);
			associatesDocument.GlobalId = "1R7R97$uLAAv4wci$KGwn8";
			IfcMaterial material = new IfcMaterial(md, "ReinforcingSteel", "", "");
			List<Point3d> points = new List<Point3d>() { new Point3d(-69.0, 0.0, -122.0), new Point3d(-69.0, 0.0, -79.0), new Point3d(-54.9411254969541, 0.0, -45.0588745030455), new Point3d(-21.0, 0.0, -31.0), new Point3d(21.0, 0.0, -31.0), new Point3d(54.9411254969541, 0.0, -45.0588745030455), new Point3d(69.0, 0.0, -78.9999999999999), new Point3d(69.0, 0.00000000000000089, -321.0), new Point3d(54.9939785957165, 1.21791490472034, -354.941125496954), new Point3d(21.1804517666074, 4.15822158551252, -369.0), new Point3d(-20.6616529376114, 7.79666547283599, -369.0), new Point3d(-54.4751797667207, 10.7369721536282, -354.941125496954), new Point3d(-68.4812011710042, 11.9548870583485, -321.0), new Point3d(-69.0, 12.0, -79.0), new Point3d(-54.9411254969541, 12.0, -45.0588745030455), new Point3d(-21.0, 12.0, -31.0), new Point3d(21.0, 12.0, -31.0), new Point3d(54.9411254969541, 12.0, -45.0588745030455), new Point3d(69.0, 12.0, -78.9999999999999),new Point3d(69.0, 12.0, -122.0), };
			PolyCurve pc = new PolyCurve();
			pc.Append(new Line(points[0],points[1]));
			pc.Append(new Arc(points[1],points[2],points[3] ));
			pc.Append(new Line(points[3],points[4]));
			pc.Append(new Arc(points[4],points[5],points[6] ));
			pc.Append(new Line(points[6],points[7]));
			pc.Append(new Arc(points[7],points[8],points[9] ));
			pc.Append(new Line(points[9],points[10]));
			pc.Append(new Arc(points[10],points[11],points[12] ));
			pc.Append(new Line(points[12],points[13]));
			pc.Append(new Arc(points[13],points[14],points[15] ));
			pc.Append(new Line(points[15],points[16]));
			pc.Append(new Arc(points[16],points[17],points[18] ));
			pc.Append(new Line(points[18],points[19]));
			IfcBoundedCurve directrix = IfcBoundedCurve.ConvertCurve(md,pc);

			double barDiameter = 12, area = Math.PI * Math.Pow( barDiameter,2) / 4;
			IfcSweptDiskSolid sweptDiskSolid = new IfcSweptDiskSolid(directrix, barDiameter/2.0, 0);
			IfcRepresentationMap representationMap = new IfcRepresentationMap(sweptDiskSolid);
			string shapeCode = ""; //Todo
			IfcReinforcingBarType reinforcingBarType = new IfcReinforcingBarType(md, "12 Diameter Ligature", IfcReinforcingBarTypeEnum.LIGATURE, barDiameter, area, 1150, IfcReinforcingBarSurfaceEnum.TEXTURED, shapeCode, null) { GlobalId = "0jMRtfHYXE7u4s_CQ2uVE9", MaterialSelect = material, RepresentationMaps = new List<IfcRepresentationMap>() { representationMap} };
			reinforcingBarType.ObjectTypeOf.GlobalId = "1iAfl2ERbFmwi7uniy1H7j";
			reinforcingBarType.Material.Associates.GlobalId = "3gfVO40P5EfQyKZ_bF0R$6";
			if (assembly)
			{
				IfcMaterial concrete = new IfcMaterial(md,"Concrete","","Concrete");
				string name = "400x200RC";
				IfcRectangleProfileDef rectangleProfileDef = new IfcRectangleProfileDef(md, name, 400, 200);
				IfcMaterialProfile materialProfile = new IfcMaterialProfile(md,name,"",concrete,rectangleProfileDef,0,"");

				IfcBeamType beamType = new IfcBeamType(name, materialProfile, IfcBeamTypeEnum.BEAM) { GlobalId = "3bdpqVuWTCbxJ2S3ODYv6q"};
				beamType.ObjectTypeOf.GlobalId = "2oaQVVf79BrwRouvtRuQVg";
				beamType.Material.Associates.GlobalId = "2ZEgyI2v184hwa$_diRqS9";
				IfcBeamStandardCase beamStandardCase = new IfcBeamStandardCase(building, beamType, new Line(0, 0, 0, 0, 5000, 0), Vector3d.ZAxis, IfcCardinalPointReference.TOPMID, null) { GlobalId = "1yjQ2DwLnCC8k3i3X6D_ut" };
				beamStandardCase.Material.Associates.GlobalId = "3DWeleqqjEG9KshbOZXUdY";
				IfcElementAssembly elementAssembly = new IfcElementAssembly(beamStandardCase, IfcAssemblyPlaceEnum.FACTORY, IfcElementAssemblyTypeEnum.REINFORCEMENT_UNIT) { GlobalId = "0Q1tCJWdj4kOkZUg7rkf2h" };
				List<string> ids = new List<string>() { "0ohBfsArr3ruXYxacT4yl5","3YrK7RbE122fNRsP5djFAe","0wxAc63nj5AezFhfks7wLL","0bsov2wZL6tRRZmKy4vuUU","3qrgfIBb92ZegJTle7jou3","16m6R3JeT83fJPCze2yU$a","2SGIIYjSbCuu3HVwoLt1yh","0PsLby6eL8_hVEt4QwK0lZ","1325VJou5AngWp1djcV0hL","20zj_$BcH74xRgR4bDrLNb","3M4SfEMtHEJukgZR4hw$eV","23BYnIaOLBZPVTrKVEDJiy","2XulRByDL8ugyo4Uqv9rJr","2xvQMSga96XOT3VeCS6ZsK","2gUE6_w3j77f8YJGz_2RMl","0J0dRL4tT93REAabfASDom","048RJ151b81PqODsTMD4EA","3hXx9Kb6b5bvjgr9pwvpz0","0FmUHg8ZX0ZfY$0f5nkM2l","2_zvpwRdvAuRiTlHXX$Qp8","1mhkXHKfX6PxdS2vZn17wX","0CeIQzUqP5qOOeAjMtH2OX","3shtoAQL5BAhvwA_1Ph$lC","22j4RNKqD2IBRDGig5eaCF","3Wvu6qGJH4ChhTV3pl9CGh","37Qrf07Iz3tRMbSxEA4ynH","2gelqZ1Wv8BvCy6TstVGkd","1Q21dHc_X7eRppCHrT69Vb","0e6Wc08NLD59ueqCAK1gxp","3xdMOSZMj3cBOV_QTbXZha","1r_U9JTkHDWwkv_nfWFHVe","29I7_S2fT3WRD4zPH4YjmD","0$ciATTaP17PJMHQD0$N3Y","1irBeCCUf82wdGg7qTPCbW" };
				int jcounter = 0;
				for (int icounter = 25; icounter < 5000; icounter += 150)
				{
					IfcElement element = reinforcingBarType.GenerateMappedItemElement(elementAssembly, new Plane(new Point3d(0, icounter, 0), Vector3d.XAxis, Vector3d.YAxis));
					element.GlobalId = ids[jcounter++];
				}
				elementAssembly.IsDecomposedBy[0].GlobalId = "1WdB196Kb72f_pKgj5rklU";
			}
			else
			{ 
				IfcElement element = reinforcingBarType.GenerateMappedItemElement(building, Plane.WorldXY);
				element.GlobalId = "0WUveBtSTDbunNjDLsuRn$";
			}
		}
Beispiel #4
0
        public void AddIfcDocumentInformation(IfcDocumentInformation ifcDocumentInformation, bool overwriteIfExists = false)
        {
            if (ifcDocumentInformation == null)
            {
                return;
            }

            //<IfcRelAssociatesDocument GlobalId="1wbA9QmR90bwuS__laYrEh">
            //  <RelatedObjects>
            //    <IfcProject ref="i1" xsi:nil="true" />
            //  </RelatedObjects>
            //  <RelatingDocument>
            //    <IfcDocumentInformation ref="i3302" xsi:nil="true" />
            //  </RelatingDocument>
            //</IfcRelAssociatesDocument>

            // ------------------------------------------------------------------------------
            var ifcRelAssociatesDocumentCollection = (from ifcRelAssociatesDocument in this.Document.IfcXmlDocument.Items.OfType <IfcRelAssociatesDocument>()
                                                      where ifcRelAssociatesDocument.RelatingDocument != null &&
                                                      ifcRelAssociatesDocument.RelatingDocument.Item != null &&
                                                      ifcRelAssociatesDocument.RelatingDocument.Item.Ref == ifcDocumentInformation.Id
                                                      select ifcRelAssociatesDocument).ToList();

            if (ifcRelAssociatesDocumentCollection.Any())
            {
                foreach (var ifcRelAssociatesDocument in ifcRelAssociatesDocumentCollection)
                {
                    if (ifcRelAssociatesDocument.RelatedObjects == null)
                    {
                        ifcRelAssociatesDocument.RelatedObjects = new IfcRelAssociatesRelatedObjects();
                    }

                    var releatedObjectsItem = ifcRelAssociatesDocument.RelatedObjects.Items.FirstOrDefault(item => item.Ref == this.Id);
                    if (releatedObjectsItem == null)
                    {
                        ifcRelAssociatesDocument.RelatedObjects.Items.Add(this.RefInstance <IfcRoot>());
                    }
                }
            }
            else
            {
                IfcRelAssociatesDocument ifcRelAssociatesDocument = new IfcRelAssociatesDocument()
                {
                    GlobalId         = Document.GetNewGlobalId(),
                    RelatingDocument = new IfcRelAssociatesDocumentRelatingDocument()
                    {
                        Item = ifcDocumentInformation.RefInstance <IfcDocumentInformation>()
                    }
                };
                ifcRelAssociatesDocument.RelatedObjects = new IfcRelAssociatesRelatedObjects();
                ifcRelAssociatesDocument.RelatedObjects.Items.Add(this.RefInstance <IfcRoot>());
                this.Document.IfcXmlDocument.Items.Add(ifcRelAssociatesDocument);
            }
        }
        public void AddRelatedObject <T>(T t) where T : IfcRoot
        {
            if (t == null)
            {
                return;
            }

            Ifc4.Document document = this.Document;
            var           ifcRelAssociatesDocumentCollection = (from ifcRelAssociatesDocument in document.IfcXmlDocument.Items.OfType <Ifc4.IfcRelAssociatesDocument>()
                                                                where ifcRelAssociatesDocument.RelatingDocument?.Item?.Ref == this.Id
                                                                select ifcRelAssociatesDocument).ToList();

            if (ifcRelAssociatesDocumentCollection.Any())
            {
                // IfcRelAssociatesDocument already exists
                foreach (var ifcRelAssociatesDocument in ifcRelAssociatesDocumentCollection)
                {
                    // add related object if not exists
                    if (
                        ifcRelAssociatesDocument.RelatedObjects != null &&
                        !ifcRelAssociatesDocument.RelatedObjects.Items.Exists(item => item.Ref == t.Id)
                        )
                    {
                        ifcRelAssociatesDocument.RelatedObjects.Items.Add(t.RefInstance <T>());
                    }
                }
            }
            else
            {
                // add new IfcRelAssociatesDocument
                IfcRelAssociatesDocument ifcRelAssociatesDocument = new IfcRelAssociatesDocument()
                {
                    GlobalId         = Document.GetNewGlobalId(),
                    RelatingDocument = new IfcRelAssociatesDocumentRelatingDocument()
                    {
                        Item = this.RefInstance <IfcDocumentInformation>()
                    }
                };
                ifcRelAssociatesDocument.RelatedObjects = new IfcRelAssociatesRelatedObjects();
                ifcRelAssociatesDocument.RelatedObjects.Items.Add(t.RefInstance <T>());
                this.Document.IfcXmlDocument.Items.Add(ifcRelAssociatesDocument);
            }
        }
        /// <summary>
        /// Fill sheet rows for Document sheet
        /// </summary>
        /// <returns>COBieSheet</returns>
        public override COBieSheet <COBieDocumentRow> Fill()
        {
            ProgressIndicator.ReportMessage("Starting Documents...");
            var ifcProject = Model.Instances.FirstOrDefault <IIfcProject>();

            Debug.Assert(ifcProject != null);

            //create new sheet
            COBieSheet <COBieDocumentRow> documents = new COBieSheet <COBieDocumentRow>(Constants.WORKSHEET_DOCUMENT);

            // get all IfcBuildingStory objects from IFC file
            IEnumerable <IfcDocumentInformation> docInfos = Model.FederatedInstances.OfType <IfcDocumentInformation>();

            ProgressIndicator.Initialise("Creating Documents", docInfos.Count());

            foreach (IfcDocumentInformation di in docInfos)
            {
                ProgressIndicator.IncrementAndUpdate();

                COBieDocumentRow doc = new COBieDocumentRow(documents);


                doc.Name = (di == null) ? "" : di.Name.ToString();
                //get the first associated document to extract the objects the document refers to
                IfcRelAssociatesDocument ifcRelAssociatesDocument = DocumentInformationForObjects(di).FirstOrDefault();


                if ((ifcRelAssociatesDocument != null) && (ifcRelAssociatesDocument.OwnerHistory != null))
                {
                    doc.CreatedBy = GetTelecomEmailAddress(ifcRelAssociatesDocument.OwnerHistory);
                }
                else if (di.DocumentOwner != null)
                {
                    if (di.DocumentOwner is IfcPersonAndOrganization)
                    {
                        doc.CreatedBy = GetTelecomEmailAddress(di.DocumentOwner as IfcPersonAndOrganization);
                    }
                    else if (di.DocumentOwner is IfcPerson)
                    {
                        doc.CreatedBy = GetEmail(null, di.DocumentOwner as IfcPerson);
                    }
                    else if (di.DocumentOwner is IfcOrganization)
                    {
                        doc.CreatedBy = GetEmail(di.DocumentOwner as IfcOrganization, null);
                    }
                }
                else if (ifcProject.OwnerHistory != null)
                {
                    doc.CreatedBy = GetTelecomEmailAddress(ifcProject.OwnerHistory);
                }


                if ((ifcRelAssociatesDocument != null) && (ifcRelAssociatesDocument.OwnerHistory != null))
                {
                    doc.CreatedOn = GetCreatedOnDateAsFmtString(ifcRelAssociatesDocument.OwnerHistory);
                }
                else if (di.CreationTime != null)
                {
                    doc.CreatedOn = di.CreationTime.ToString();
                }
                else if (ifcProject.OwnerHistory != null)
                {
                    doc.CreatedOn = Context.RunDateTime;
                }


                doc.Category = (string.IsNullOrEmpty(di.Purpose.ToString())) ? DEFAULT_STRING :di.Purpose.ToString();

                doc.ApprovalBy = (string.IsNullOrEmpty(di.IntendedUse.ToString())) ? DEFAULT_STRING : di.IntendedUse.ToString();
                doc.Stage      = (string.IsNullOrEmpty(di.Scope.ToString())) ? DEFAULT_STRING : di.Scope.ToString();


                RelatedObjectInformation relatedObjectInfo = GetRelatedObjectInformation(ifcRelAssociatesDocument);
                doc.SheetName     = relatedObjectInfo.SheetName;
                doc.RowName       = relatedObjectInfo.Name;
                doc.ExtObject     = relatedObjectInfo.ExtObject;
                doc.ExtIdentifier = relatedObjectInfo.ExtIdentifier;
                doc.ExtSystem     = relatedObjectInfo.ExtSystem;

                if (ifcRelAssociatesDocument != null)
                {
                    FileInformation fileInfo = GetFileInformation(ifcRelAssociatesDocument);
                    doc.File      = fileInfo.Name;
                    doc.Directory = GetDirectory(!string.IsNullOrWhiteSpace(fileInfo.Location) ? fileInfo.Location : fileInfo.Name);
                }

                doc.Description = (string.IsNullOrEmpty(di.Description)) ? DEFAULT_STRING : di.Description.ToString();
                doc.Reference   = (string.IsNullOrEmpty(di.DocumentId.Value.ToString())) ? DEFAULT_STRING : di.DocumentId.Value.ToString();

                documents.AddRow(doc);
            }

            documents.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();
            return(documents);
        }
        /// <summary>
        /// Get the file information for the document attached to the ifcRelAssociatesDocument
        /// </summary>
        /// <param name="ifcRelAssociatesDocument">IfcRelAssociatesDocument object</param>
        /// <returns>FileInformation structure </returns>
        private FileInformation GetFileInformation(IfcRelAssociatesDocument ifcRelAssociatesDocument)
        {
            FileInformation DocInfo = new FileInformation()
            {
                Name = DEFAULT_STRING, Location = DEFAULT_STRING
            };
            string value = "";

            if (ifcRelAssociatesDocument != null)
            {
                //test for single document
                IfcDocumentReference ifcDocumentReference = ifcRelAssociatesDocument.RelatingDocument as IfcDocumentReference;
                if (ifcDocumentReference != null)
                {
                    //this is possibly incorrect, think it references information within a document
                    value = ifcDocumentReference.ItemReference.ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        DocInfo.Name = value;
                    }
                    value = ifcDocumentReference.Location.ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        DocInfo.Location = value;
                    }
                }
                else //test for a document list
                {
                    IfcDocumentInformation ifcDocumentInformation = ifcRelAssociatesDocument.RelatingDocument as IfcDocumentInformation;
                    if (ifcDocumentInformation != null)
                    {
                        IEnumerable <IfcDocumentReference> ifcDocumentReferences = ifcDocumentInformation.DocumentReferences;
                        if (ifcDocumentReferences != null)
                        {
                            List <string> strNameValues     = new List <string>();
                            List <string> strLocationValues = new List <string>();
                            foreach (IfcDocumentReference docRef in ifcDocumentReferences)
                            {
                                //get file name
                                value = docRef.ItemReference.ToString();
                                if (!string.IsNullOrEmpty(value))
                                {
                                    strNameValues.Add(value);
                                }
                                else
                                {
                                    value = docRef.Name.ToString();
                                    if (!string.IsNullOrEmpty(value))
                                    {
                                        strNameValues.Add(value);
                                    }
                                }
                                //get file location
                                value = docRef.Location.ToString();
                                if ((!string.IsNullOrEmpty(value)) && (!strNameValues.Contains(value)))
                                {
                                    strLocationValues.Add(value);
                                }
                            }
                            //set values to return
                            if (strNameValues.Count > 0)
                            {
                                DocInfo.Name = COBieXBim.JoinStrings(':', strNameValues);
                            }
                            if (strLocationValues.Count > 0)
                            {
                                DocInfo.Location = COBieXBim.JoinStrings(':', strLocationValues);
                            }
                        }
                    }
                }
            }
            return(DocInfo);
        }
Beispiel #8
0
        public override void Run()

        {
            using (var txn = model.BeginTransaction("Example creation"))
            {
                IfcProject        project           = model.Instances.New <IfcProject>(p => p.Name = "TriluxLightingProducts");
                IfcUnitAssignment ifcUnitAssignment = model.Instances.New <IfcUnitAssignment>(ua =>
                {
                    ua.Units.Add(model.Instances.New <IfcSIUnit>(u =>
                    {
                        u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.LENGTHUNIT;
                        u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.METRE;
                        u.Prefix   = Xbim.Ifc4.Interfaces.IfcSIPrefix.MILLI;
                    }));
                    ua.Units.Add(model.Instances.New <IfcSIUnit>(u =>
                    {
                        u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.MASSUNIT;
                        u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.GRAM;
                        u.Prefix   = Xbim.Ifc4.Interfaces.IfcSIPrefix.KILO;
                    }));
                });


                //Insert Classification system
                var ifcClassificationSystemOmniClass = model.Instances.New <IfcClassification>(cs =>
                {
                    cs.Name        = "Omniclass";
                    cs.Edition     = "1.0";
                    cs.EditionDate = "2018-12-27T00:00:00.0000000";
                    cs.Description = "The OmniClass Construction Classification System (known as OmniClass™ or OCCS) is a classification system for the construction industry. OmniClass is useful for many applications, from organizing library materials, product literature, and project information, to providing a classification structure for electronic databases. It incorporates other extant systems currently in use as the basis of many of its Tables – MasterFormat™ for work results, UniFormat for elements, and EPIC (Electronic Product Information Cooperation) for structuring products.";
                    cs.Location    = "http://www.omniclass.org/";
                });

                //Insertion of some sample classification references
                //I would be better to insert the whole classification system and reference the appropriate code
                var ifcClassificationReferenceOmniClass = model.Instances.New <IfcClassificationReference>(cr =>
                {
                    cr.Identification   = "23-35-47";
                    cr.Name             = "Electrical Lighting";
                    cr.Description      = "";
                    cr.ReferencedSource = ifcClassificationSystemOmniClass;
                });

                var ifcRelAssociatesClassificationOmniClass = model.Instances.New <IfcRelAssociatesClassification>(relc =>
                {
                    relc.RelatingClassification = ifcClassificationReferenceOmniClass;
                });

                //Insert Classification system
                var ifcClassificationSystemUniClass = model.Instances.New <IfcClassification>(cs =>
                {
                    cs.Name        = "Uniclass";
                    cs.Edition     = "2015";
                    cs.EditionDate = "01.01.2015";
                    cs.Description = "Uniclass is a voluntary classification system for the construction industry that can be used for structuring project information, such as building information models (BIM).";
                    cs.Location    = "https://www.thenbs.com/our-tools/introducing-uniclass-2015";
                });

                //Insertion of some sample classification references
                //I would be better to insert the whole classification system and reference the appropriate code
                var ifcClassificationReferenceUniClass = model.Instances.New <IfcClassificationReference>(cr =>
                {
                    cr.Identification   = "CA-70-10-30";
                    cr.Name             = "Site lighting equipment";
                    cr.Description      = "";
                    cr.ReferencedSource = ifcClassificationSystemUniClass;
                });

                var ifcRelAssociatesClassificationUniClass = model.Instances.New <IfcRelAssociatesClassification>(relc =>
                {
                    relc.RelatingClassification = ifcClassificationReferenceUniClass;
                });

                //Insert a project library to store the product data templates and type products

                var ifcProductDataLibrary = model.Instances.New <IfcProjectLibrary>(l => {
                    l.Name         = "TriluxLightingProductsLibrary";
                    l.GlobalId     = "1DbshdzGD71ejurQqQcxbw";
                    l.Description  = "Library for Trilux light fixtures product data templates based on the ZVEI European core properties";
                    l.Phase        = "Design,Build,Operate";
                    l.OwnerHistory = model.Instances.New <IfcOwnerHistory>(oh =>
                    {
                        oh.CreationDate = DateTime.Now;
                        //oh.ChangeAction = Xbim.Ifc4.Interfaces.IfcChangeActionEnum.ADDED;
                        oh.OwningUser = model.Instances.New <IfcPersonAndOrganization>(po =>
                        {
                            po.TheOrganization = model.Instances.New <IfcOrganization>(o =>
                            {
                                o.Name = "TRILUX GmbH & Co. KG";
                            });

                            po.ThePerson = model.Instances.New <IfcPerson>(p =>
                            {
                                p.GivenName  = "Robert";
                                p.FamilyName = "Heinze";
                            });
                        });
                        oh.OwningApplication = model.Instances.New <IfcApplication>(app =>
                        {
                            app.ApplicationIdentifier = "ID_OF_PIM-SYSTEM";
                            app.ApplicationFullName   = "My Product Information System (PIM)";
                            app.ApplicationDeveloper  = model.Instances.New <IfcOrganization>(o =>
                            {
                                o.Name = "The software company, that developed the PIM system";
                            });
                            app.Version = "1.0";
                        });
                    });
                });

                Comment(ifcProductDataLibrary, @"Root element of this file. Because this doesn't define a specific instance in the building it is a library. It can be used to declare elements, properties, property templates and other library objects which can be later used in the actual design.");
                Comment(ifcProductDataLibrary.OwnerHistory, @"Owner history is used to define ownership of the information.");

                var ifcProductDataLibraryDeclarations = New <IfcRelDeclares>(rel =>
                {
                    rel.RelatingContext = ifcProductDataLibrary;
                }).RelatedDefinitions;
                Comment(ifcProductDataLibraryDeclarations.OwningEntity, @"This relation points to all definitions declared within the scope of the library. These can be elements, element types, properties or property templates");


                //Creating an IfcPropertySetTemplate manually
                //This is not optimal
                //Instead of creating the IfcPropertySetTemplates manually,
                //they should be loaded from the publishing dictionary


                //Read templates from excel sheet
                var          workbookTemplates  = new XLWorkbook(Path.Combine(sourceFolder, sourceFile));
                IXLWorksheet worksheetTemplates = workbookTemplates.Worksheet("Templates");
                //IXLRange rangeTemplates = worksheetTemplates.Range("A1:Z690");
                //IXLTable rawDataTemplates = rangeTemplates.AsTable();
                DataTable dtTemplates = ReadDataTable(worksheetTemplates);

                var productDataTemplates = from DataRow dr in dtTemplates.Rows orderby dr["DataTemplate"] group dr by dr["DataTemplate"];
                foreach (var productDataTemplate in productDataTemplates)
                {
                    IfcPropertySetTemplate ifcPropertySetTemplate = model.Instances.New <IfcPropertySetTemplate>(pset =>
                    {
                        pset.GlobalId         = Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId.ConvertToBase64(Guid.NewGuid());
                        pset.Name             = productDataTemplate.Key.ToString();
                        pset.Description      = "Data Template by " + productDataTemplate.ElementAt(0)["Publisher"].ToString();
                        pset.ApplicableEntity = "IfcBuildingElementProxy/USERDEFINED";
                        pset.TemplateType     = Xbim.Ifc4.Interfaces.IfcPropertySetTemplateTypeEnum.PSET_TYPEDRIVENONLY;
                    });
                    Comment(ifcPropertySetTemplate, @"Declaration of 'IfcPropertySetTemplate' within the library for lighting product data templates.");
                    Comment(ifcPropertySetTemplate, @"Insert property templates; they should be loaded from the publishing dictionary");

                    foreach (DataRow propertyTemplate in productDataTemplate)
                    {
                        IfcSimplePropertyTemplate ifcSimplePropertyTemplate = model.Instances.New <IfcSimplePropertyTemplate>(spt =>
                        {
                            spt.Name               = propertyTemplate["SystemName"].ToString();
                            spt.Description        = propertyTemplate["Definition"].ToString();
                            spt.Expression         = "";
                            spt.GlobalId           = GetGuid(propertyTemplate["GlobalId"].ToString());
                            spt.TemplateType       = Xbim.Ifc4.Interfaces.IfcSimplePropertyTemplateTypeEnum.P_SINGLEVALUE;
                            spt.AccessState        = Xbim.Ifc4.Interfaces.IfcStateEnum.LOCKED;
                            spt.PrimaryMeasureType = propertyTemplate["PrimaryMeasureType"].ToString();

                            //check if enum values exists in this template, and if, create themn in IFC
                            string allowedValues = propertyTemplate["AllowedValues"].ToString();
                            if (allowedValues.Length > 0)
                            {
                                spt.TemplateType = IfcSimplePropertyTemplateTypeEnum.P_ENUMERATEDVALUE;
                                IfcPropertyEnumeration ifcPropertyEnumeration = model.Instances.New <IfcPropertyEnumeration>(pe =>
                                {
                                    pe.Name = $"Allowed values of {spt.Name}";
                                });

                                char delimiter = '|';
                                foreach (string allowedValue in allowedValues.Split(delimiter))
                                {
                                    ifcPropertyEnumeration.EnumerationValues.Add(new IfcLabel(allowedValue));
                                }

                                spt.Enumerators = ifcPropertyEnumeration;
                            }

                            //Check the measures and units
                            string primaryMeasureType = propertyTemplate["PrimaryMeasureType"].ToString();
                            if ((primaryMeasureType == "IfcDocumentInformation") ||
                                (primaryMeasureType == "IfcClassificationReference") ||
                                (primaryMeasureType == "IfcGloballyUniqueId"))
                            {
                                spt.PrimaryMeasureType = "IfcLabel";
                            }
                            else if (primaryMeasureType == typeof(IfcLengthMeasure).Name)
                            {
                                spt.PrimaryUnit = model.Instances.New <IfcSIUnit>(u =>
                                {
                                    u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.LENGTHUNIT;
                                    u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.METRE;
                                    u.Prefix   = Xbim.Ifc4.Interfaces.IfcSIPrefix.MILLI;
                                });
                            }
                            else if (primaryMeasureType == typeof(IfcMassMeasure).Name)
                            {
                                spt.PrimaryUnit = model.Instances.New <IfcSIUnit>(u =>
                                {
                                    u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.MASSUNIT;
                                    u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.GRAM;
                                });
                            }
                            else if (primaryMeasureType == typeof(IfcPlaneAngleMeasure).Name)
                            {
                                spt.PrimaryUnit = model.Instances.New <IfcConversionBasedUnit>(punit =>
                                {
                                    //Convert the angel measure from the unit grad to the SI Unit radian
                                    //rad=grad*(PI/180)
                                    punit.Name             = "Grad";
                                    punit.UnitType         = Xbim.Ifc4.Interfaces.IfcUnitEnum.PLANEANGLEUNIT;
                                    punit.ConversionFactor = model.Instances.New <IfcMeasureWithUnit>(mwu =>
                                    {
                                        mwu.UnitComponent = model.Instances.New <IfcSIUnit>(siUnit =>
                                        {
                                            siUnit.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.PLANEANGLEUNIT;
                                            siUnit.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.RADIAN;
                                        });
                                        mwu.ValueComponent = new IfcReal(Math.PI / 180);
                                    });
                                    punit.Dimensions = model.Instances.New <IfcDimensionalExponents>(dim =>
                                    {
                                        dim.LengthExponent                   = 0;
                                        dim.MassExponent                     = 0;
                                        dim.TimeExponent                     = 0;
                                        dim.ElectricCurrentExponent          = 0;
                                        dim.ThermodynamicTemperatureExponent = 0;
                                        dim.AmountOfSubstanceExponent        = 0;
                                        dim.LuminousIntensityExponent        = 0;
                                    });
                                });
                            }
                        });


                        string complexGroupName = propertyTemplate["ComplexGroupName"].ToString();
                        if (complexGroupName.Length == 0)
                        {
                            ifcPropertySetTemplate.HasPropertyTemplates.Add(ifcSimplePropertyTemplate);
                        }
                        else
                        {
                            //Find the appropriate IfcComplexPropertyTemplate, and if it does not yet exist, create it
                            IfcComplexPropertyTemplate ifcComplexPropertyTemplate
                                = model.Instances.OfType <IfcComplexPropertyTemplate>()
                                  .Where(cpt => cpt.Name == complexGroupName)
                                  .FirstOrDefault();

                            if (ifcComplexPropertyTemplate == null)
                            {
                                ifcComplexPropertyTemplate = model.Instances.New <IfcComplexPropertyTemplate>(cpt =>
                                {
                                    cpt.Name        = complexGroupName;
                                    cpt.Description = propertyTemplate["ComplexGroupDescription"].ToString();
                                    cpt.GlobalId    = GetGuid(propertyTemplate["ComplexGroupGuid"].ToString());
                                });

                                ifcPropertySetTemplate.HasPropertyTemplates.Add(ifcComplexPropertyTemplate);
                            }

                            ifcComplexPropertyTemplate.HasPropertyTemplates.Add(ifcSimplePropertyTemplate);
                        }
                    }

                    ifcProductDataLibraryDeclarations.Add(ifcPropertySetTemplate);
                }

                //Read source data from excel sheet
                var          workbookData  = new XLWorkbook(Path.Combine(sourceFolder, sourceFile));
                IXLWorksheet worksheetData = workbookData.Worksheet("Sheets");
                //IXLRange rangeData = worksheetData.Range("A1:Z690");
                //IXLTable rawData = rangeData.AsTable();
                DataTable dtData = ReadDataTable(worksheetData);

                //Loop through the products in the data sheet
                foreach (DataRow product in dtData.Rows)
                {
                    var ifcTypeProduct = model.Instances.New <IfcTypeProduct>();
                    ifcTypeProduct.Name                 = product["Name"].ToString();
                    ifcTypeProduct.Description          = "Description of " + ifcTypeProduct.Name;
                    ifcTypeProduct.ApplicableOccurrence = "IfcLightFixture";

                    //Create the property sets, and relate them to their templates
                    foreach (IfcPropertySetTemplate ifcPropertySetTemplate in model.Instances.OfType <IfcPropertySetTemplate>().ToList())
                    {
                        IfcPropertySet ifcPropertySet = model.Instances.New <IfcPropertySet>(pset =>
                        {
                            pset.Name        = ifcPropertySetTemplate.Name;
                            pset.Description = ifcPropertySetTemplate.Description;
                        });

                        ifcTypeProduct.HasPropertySets.Add(ifcPropertySet);

                        //Relate the property set to the definition of the property set template
                        //Find the appropriate relation, and if it does not yet exist, create it
                        IfcRelDefinesByTemplate ifcRelDefinesByTemplate
                            = model.Instances.OfType <IfcRelDefinesByTemplate>()
                              .Where(rdbt => rdbt.RelatingTemplate == ifcPropertySetTemplate)
                              .FirstOrDefault();

                        if (ifcRelDefinesByTemplate == null)
                        {
                            ifcRelDefinesByTemplate = New <IfcRelDefinesByTemplate>(dbt =>
                            {
                                dbt.RelatingTemplate = ifcPropertySetTemplate;
                            });
                        }

                        ifcRelDefinesByTemplate.RelatedPropertySets.Add(ifcPropertySet);
                    }

                    //loop through the properties of the product, based on the data template
                    foreach (DataRow propertyTemplate in dtTemplates.Rows)
                    {
                        //Load the correct IfcPropertySet for this property, that was created above
                        IfcPropertySet ifcPropertySet = (IfcPropertySet)ifcTypeProduct.HasPropertySets
                                                        .Where(x => x.Name == propertyTemplate["DataTemplate"].ToString())
                                                        .FirstOrDefault();

                        //Check, which measure type the property is based on
                        switch (propertyTemplate["PrimaryMeasureType"].ToString())
                        {
                        case "IfcGloballyUniqueId":
                            //Insert the unique number for the product type
                            ifcTypeProduct.GlobalId = GetGuid(product[propertyTemplate["SystemName"].ToString()].ToString());
                            break;

                        case "IfcDocumentInformation":
                            //Insert the product information that are in documents
                            string folderName = propertyTemplate["SystemName"].ToString();
                            string docName    = product[propertyTemplate["SystemName"].ToString()].ToString();
                            if (docName.Length > 0)
                            {
                                string fileLocation = $"{folderName}/{docName}";

                                IfcDocumentInformation ifcDocumentInformation;
                                var existingInsertedDocumentInformation = model.Instances.OfType <IfcDocumentInformation>().Where(x => x.Location == fileLocation);
                                if (existingInsertedDocumentInformation.Count() == 0)
                                {
                                    ifcDocumentInformation = model.Instances.New <IfcDocumentInformation>(doc =>
                                    {
                                        doc.Identification   = docName;
                                        doc.Name             = docName;
                                        doc.Location         = $@"{folderName}/{docName}";
                                        doc.CreationTime     = DateTime.Now.ToString("dd.MM.yyyy");
                                        doc.Confidentiality  = Xbim.Ifc4.Interfaces.IfcDocumentConfidentialityEnum.PUBLIC;
                                        doc.ElectronicFormat = MimeTypes.GetMimeType(docName);
                                        doc.IntendedUse      = "Product information";
                                        doc.Purpose          = "Product information";
                                        doc.ValidFrom        = "01.01.2018";
                                        doc.ValidUntil       = "31.12.2021";
                                        doc.Scope            = "Europa";
                                        doc.Revision         = "1.0";
                                    });

                                    string test = Path.GetExtension(docName);
                                    switch (Path.GetExtension(docName))
                                    {
                                    case ".pdf":
                                        ifcDocumentInformation.Description = "Produktdatenblatt";
                                        break;

                                    case ".3ds":
                                        ifcDocumentInformation.Description = "3D-Visualisierung";
                                        break;

                                    case ".jpg":
                                        ifcDocumentInformation.Description = "Produktphoto";
                                        break;

                                    case ".ies":
                                        ifcDocumentInformation.Description = "Lichtverteilung von IES Standard";
                                        break;
                                    }


                                    IfcRelAssociatesDocument ifcRelAssociatesDocument = model.Instances.New <IfcRelAssociatesDocument>(docref =>
                                    {
                                        docref.RelatedObjects.Add(ifcTypeProduct);
                                        docref.RelatingDocument = ifcDocumentInformation;
                                    });
                                }
                                else
                                {
                                    ifcDocumentInformation = existingInsertedDocumentInformation.FirstOrDefault();
                                    var existingDocumentInformationRelation = model.Instances.OfType <IfcRelAssociatesDocument>()
                                                                              .Where(x => x.RelatingDocument == ifcDocumentInformation).FirstOrDefault();

                                    existingDocumentInformationRelation.RelatedObjects.Add(ifcTypeProduct);
                                }
                            }
                            break;

                        case "IfcClassificationReference":

                            switch (propertyTemplate["SystemName"].ToString())
                            {
                            case "Omniclass":
                                var classificationReference = model.Instances.OfType <IfcClassificationReference>()
                                                              .Where(x => x.Identification == product[propertyTemplate["SystemName"].ToString()].ToString()).FirstOrDefault();

                                ifcRelAssociatesClassificationOmniClass.RelatedObjects.Add(ifcTypeProduct);
                                break;

                            case "Uniclass":

                                ifcRelAssociatesClassificationUniClass.RelatedObjects.Add(ifcTypeProduct);
                                break;
                            }

                            break;

                        default:

                            IfcPropertySingleValue ifcPropertySingleValue
                                = model.Instances.New <IfcPropertySingleValue>(p =>
                            {
                                string propertyName = propertyTemplate["SystemName"].ToString();
                                var dataValue       = product[propertyName];

                                p.Name        = propertyName;
                                p.Description = "";

                                string primaryMeasureType = propertyTemplate["PrimaryMeasureType"].ToString();
                                if (primaryMeasureType == typeof(IfcLengthMeasure).Name)
                                {
                                    p.NominalValue = new IfcMassMeasure(Double.Parse(dataValue.ToString()));
                                }
                                else if (primaryMeasureType == typeof(IfcMassMeasure).Name)
                                {
                                    p.NominalValue = new IfcMassMeasure(Double.Parse(dataValue.ToString()));
                                }
                                else if (primaryMeasureType == typeof(IfcPlaneAngleMeasure).Name)
                                {
                                    p.NominalValue = new IfcPlaneAngleMeasure(Double.Parse(dataValue.ToString()));
                                }
                                else
                                {
                                    p.NominalValue = new IfcLabel(dataValue.ToString());
                                }
                            });


                            // Check, if the template of this property is part of a complex property
                            if (propertyTemplate["ComplexGroupName"].ToString().Length > 0)
                            {
                                string complexPropertyName        = propertyTemplate["ComplexGroupName"].ToString();
                                string complexPropertyDescription = propertyTemplate["ComplexGroupDescription"].ToString();
                                string complexPropertyGlobalId    = GetGuid(propertyTemplate["ComplexGroupGuid"].ToString());

                                IfcComplexProperty ifcComplexProperty = model.Instances
                                                                        .OfType <IfcComplexProperty>()
                                                                        .Where(n => n.Name == complexPropertyName)
                                                                        .Where(u => u.UsageName == ifcTypeProduct.Name.ToString())
                                                                        .FirstOrDefault();

                                if (ifcComplexProperty == null)
                                {
                                    ifcComplexProperty = model.Instances.New <IfcComplexProperty>(p =>
                                    {
                                        p.Name        = complexPropertyName;
                                        p.Description = complexPropertyDescription;
                                        p.UsageName   = ifcTypeProduct.Name.ToString();
                                    });
                                    ifcPropertySet.HasProperties.Add(ifcComplexProperty);
                                }

                                //Insert the product information into the complex property and then into the property set
                                ifcComplexProperty.HasProperties.Add(ifcPropertySingleValue);
                            }
                            else
                            {
                                //Insert the product information directly into the property set
                                ifcPropertySet.HasProperties.Add(ifcPropertySingleValue);
                            }

                            break;
                        }
                    }
                    ;

                    ifcProductDataLibraryDeclarations.Add(ifcTypeProduct);
                    Comment(ifcTypeProduct, @"Declaration of 'IfcTypeProduct' within the library for a ligthing product.");
                }

                txn.Commit();
            }

            string targetFileName = Path.Combine(targetFolder, targetFile);

            SaveAs(targetFileName, false, typeof(IfcProjectLibrary));

            //DirtyFix with Schema location
            //https://github.com/xBimTeam/XbimEssentials/issues/288
            string contentOfFile        = File.ReadAllText($"{targetFileName}.ifcXML");
            string oldNameSpaceLocation = @"xsi:schemaLocation=""http://www.buildingsmart-tech.org/ifcXML/IFC4/Add2 http://www.buildingsmart-tech.org/ifc/IFC4/Add2/IFC4_ADD2.xsd""";
            string newNameSpaceLocation = @"xsi:schemaLocation=""http://www.buildingsmart-tech.org/ifcXML/IFC4/Add2 ../../IFC4_ADD2.xsd""";

            contentOfFile = contentOfFile.Replace(oldNameSpaceLocation, newNameSpaceLocation);
            File.WriteAllText($"{targetFileName}.ifcXML", contentOfFile);


            //Create ifcZip file
            File.Delete(targetzipFile);
            ZipFile.CreateFromDirectory(sourceFolder, targetzipFile);
            using (ZipArchive zipArchive = ZipFile.Open(targetzipFile, ZipArchiveMode.Update))
            {
                zipArchive.GetEntry(sourceFile).Delete();
                zipArchive.CreateEntryFromFile($"{targetFolder}/{targetFile}.ifcXML", $"{targetFile}.ifcXML");
                zipArchive.CreateEntryFromFile($"{targetFolder}/{targetFile}.ifc", $"{targetFile}.ifc");
            }
        }
Beispiel #9
0
        internal static void GenerateInstance(IfcBuilding building, bool assembly)
        {
            DatabaseIfc          db = building.Database;
            IfcDocumentReference documentReference = new IfcDocumentReference(db)
            {
                Name = "MyReinforcementCode", Identification = "MyCodeISO3766"
            };
            IfcRelAssociatesDocument associatesDocument = new IfcRelAssociatesDocument(db.Project, documentReference)
            {
                GlobalId = "1R7R97$uLAAv4wci$KGwn8"
            };
            IfcMaterial material = new IfcMaterial(db, "ReinforcingSteel");
            List <Tuple <double, double, double> > points = new List <Tuple <double, double, double> >()
            {
                new Tuple <double, double, double>(-69.0, 0.0, -122.0), new Tuple <double, double, double>(-69.0, 0.0, -79.0), new Tuple <double, double, double>(-54.9411254969541, 0.0, -45.0588745030455), new Tuple <double, double, double>(-21.0, 0.0, -31.0), new Tuple <double, double, double>(21.0, 0.0, -31.0), new Tuple <double, double, double>(54.9411254969541, 0.0, -45.0588745030455), new Tuple <double, double, double>(69.0, 0.0, -78.9999999999999), new Tuple <double, double, double>(69.0, 0.00000000000000089, -321.0), new Tuple <double, double, double>(54.9939785957165, 1.21791490472034, -354.941125496954), new Tuple <double, double, double>(21.1804517666074, 4.15822158551252, -369.0), new Tuple <double, double, double>(-20.6616529376114, 7.79666547283599, -369.0), new Tuple <double, double, double>(-54.4751797667207, 10.7369721536282, -354.941125496954), new Tuple <double, double, double>(-68.4812011710042, 11.9548870583485, -321.0), new Tuple <double, double, double>(-69.0, 12.0, -79.0), new Tuple <double, double, double>(-54.9411254969541, 12.0, -45.0588745030455), new Tuple <double, double, double>(-21.0, 12.0, -31.0), new Tuple <double, double, double>(21.0, 12.0, -31.0), new Tuple <double, double, double>(54.9411254969541, 12.0, -45.0588745030455), new Tuple <double, double, double>(69.0, 12.0, -78.9999999999999), new Tuple <double, double, double>(69.0, 12.0, -122.0),
            };
            IfcBoundedCurve directrix = null;

            if (db.Release == ReleaseVersion.IFC2x3)
            {
                directrix = new IfcPolyline(db, points);
            }
            else
            {
                List <IfcSegmentIndexSelect> segments = new List <IfcSegmentIndexSelect>();
                segments.Add(new IfcLineIndex(1, 2));
                segments.Add(new IfcArcIndex(2, 3, 4));
                segments.Add(new IfcLineIndex(4, 5));
                segments.Add(new IfcArcIndex(5, 6, 7));
                segments.Add(new IfcLineIndex(7, 8));
                segments.Add(new IfcArcIndex(8, 9, 10));
                segments.Add(new IfcLineIndex(10, 11));
                segments.Add(new IfcArcIndex(11, 12, 13));
                segments.Add(new IfcLineIndex(13, 14));
                segments.Add(new IfcArcIndex(14, 15, 16));
                segments.Add(new IfcLineIndex(16, 17));
                segments.Add(new IfcArcIndex(17, 18, 19));
                segments.Add(new IfcLineIndex(19, 20));
                directrix = new IfcIndexedPolyCurve(new IfcCartesianPointList3D(db, points), segments);
            }
            double                barDiameter = 12, area = Math.PI * Math.Pow(barDiameter, 2) / 4;
            IfcSweptDiskSolid     sweptDiskSolid     = new IfcSweptDiskSolid(directrix, barDiameter / 2.0);
            IfcRepresentationMap  representationMap  = new IfcRepresentationMap(sweptDiskSolid);
            string                shapeCode          = ""; //Todo
            IfcReinforcingBarType reinforcingBarType = new IfcReinforcingBarType(db, "12 Diameter Ligature", IfcReinforcingBarTypeEnum.LIGATURE, barDiameter, area, 1150, IfcReinforcingBarSurfaceEnum.TEXTURED, shapeCode, null)
            {
                GlobalId = "0jMRtfHYXE7u4s_CQ2uVE9", MaterialSelect = material
            };

            reinforcingBarType.RepresentationMaps.Add(representationMap);
            db.Context.AddDeclared(reinforcingBarType);
            if (assembly)
            {
                IfcMaterial concrete = new IfcMaterial(db, "Concrete")
                {
                    Category = "Concrete"
                };
                string name = "400x200RC";
                IfcRectangleProfileDef rectangleProfileDef = new IfcRectangleProfileDef(db, name, 200, 400);
                IfcMaterialProfile     materialProfile     = new IfcMaterialProfile(name, concrete, rectangleProfileDef);

                IfcBeamType beamType = new IfcBeamType(name, materialProfile, IfcBeamTypeEnum.BEAM);
                db.Context.AddDeclared(beamType);
                IfcMaterialProfileSet materialProfileSet = beamType.MaterialSelect as IfcMaterialProfileSet;
                IfcBeam beam = new IfcBeam(building, new IfcLocalPlacement(building.Placement, new IfcAxis2Placement3D(new IfcCartesianPoint(db, 0, 0, 0))), null)
                {
                    Description = "Reinforced Beam"
                };
                IfcBeamStandardCase beamStandardCase = new IfcBeamStandardCase(beam, new IfcMaterialProfileSetUsage(materialProfileSet, IfcCardinalPointReference.TOPMID), new IfcAxis2Placement3D(new IfcCartesianPoint(db, 0, 0, 0), new IfcDirection(db, 0, 1, 0), new IfcDirection(db, -1, 0, 0)), 5000)
                {
                    GlobalId = "1yjQ2DwLnCC8k3i3X6D_ut", RelatingType = beamType
                };
                IfcElementAssembly elementAssembly = new IfcElementAssembly(beam, IfcAssemblyPlaceEnum.FACTORY, IfcElementAssemblyTypeEnum.REINFORCEMENT_UNIT);
                List <string>      ids             = new List <string>()
                {
                    "0ohBfsArr3ruXYxacT4yl5", "3YrK7RbE122fNRsP5djFAe", "0wxAc63nj5AezFhfks7wLL", "0bsov2wZL6tRRZmKy4vuUU", "3qrgfIBb92ZegJTle7jou3", "16m6R3JeT83fJPCze2yU$a", "2SGIIYjSbCuu3HVwoLt1yh", "0PsLby6eL8_hVEt4QwK0lZ", "1325VJou5AngWp1djcV0hL", "20zj_$BcH74xRgR4bDrLNb", "3M4SfEMtHEJukgZR4hw$eV", "23BYnIaOLBZPVTrKVEDJiy", "2XulRByDL8ugyo4Uqv9rJr", "2xvQMSga96XOT3VeCS6ZsK", "2gUE6_w3j77f8YJGz_2RMl", "0J0dRL4tT93REAabfASDom", "048RJ151b81PqODsTMD4EA", "3hXx9Kb6b5bvjgr9pwvpz0", "0FmUHg8ZX0ZfY$0f5nkM2l", "2_zvpwRdvAuRiTlHXX$Qp8", "1mhkXHKfX6PxdS2vZn17wX", "0CeIQzUqP5qOOeAjMtH2OX", "3shtoAQL5BAhvwA_1Ph$lC", "22j4RNKqD2IBRDGig5eaCF", "3Wvu6qGJH4ChhTV3pl9CGh", "37Qrf07Iz3tRMbSxEA4ynH", "2gelqZ1Wv8BvCy6TstVGkd", "1Q21dHc_X7eRppCHrT69Vb", "0e6Wc08NLD59ueqCAK1gxp", "3xdMOSZMj3cBOV_QTbXZha", "1r_U9JTkHDWwkv_nfWFHVe", "29I7_S2fT3WRD4zPH4YjmD", "0$ciATTaP17PJMHQD0$N3Y", "1irBeCCUf82wdGg7qTPCbW"
                };
                int jcounter = 0;
                for (int icounter = 25; icounter < 5000; icounter += 150)
                {
                    IfcElement element = reinforcingBarType.GenerateMappedItemElement(elementAssembly, new IfcCartesianTransformationOperator3D(db)
                    {
                        LocalOrigin = new IfcCartesianPoint(db, 0, icounter, 0)
                    });
                    //Unique ids assigned to generate constant IfcScript  sample files, remove otherwise
                    element.GlobalId = ids[jcounter++];
                }

                //Unique ids assigned to generate constant IfcScript  sample files, remove otherwise
                beam.GlobalId     = "1_KSmTR8T8bO37iRs24GkM";
                beamType.GlobalId = "3bdpqVuWTCbxJ2S3ODYv6q";
                beamType.ObjectTypeOf.GlobalId = "2oaQVVf79BrwRouvtRuQVg";
                beamType.MaterialSelect.Associates.GlobalId         = "2ZEgyI2v184hwa$_diRqS9";
                beamStandardCase.MaterialSelect.Associates.GlobalId = "3DWeleqqjEG9KshbOZXUdY";
                elementAssembly.GlobalId = "0Q1tCJWdj4kOkZUg7rkf2h";
                elementAssembly.IsDecomposedBy[0].GlobalId = "1WdB196Kb72f_pKgj5rklU";
                beam.IsDecomposedBy[0].GlobalId            = "1b1SnKocD0WRevlg8Aqhj5";
            }
            else
            {
                IfcElement element = reinforcingBarType.GenerateMappedItemElement(building, new IfcCartesianTransformationOperator3D(db));

                //Unique ids assigned to generate constant IfcScript  sample files, remove otherwise
                element.GlobalId = "0WUveBtSTDbunNjDLsuRn$";
            }

            //Unique ids assigned to generate constant IfcScript  sample files, remove otherwise

            reinforcingBarType.ObjectTypeOf.GlobalId = "1iAfl2ERbFmwi7uniy1H7j";
            reinforcingBarType.MaterialSelect.Associates.GlobalId = "3gfVO40P5EfQyKZ_bF0R$6";
        }
Beispiel #10
0
        internal static void GenerateData(STPModelData md, IfcBuilding building, bool assembly)
        {
            IfcDocumentReference     documentReference  = new IfcDocumentReference(md, "", "MyReinforcementCode", "MyCodeISO3766", "", null);
            IfcRelAssociatesDocument associatesDocument = new IfcRelAssociatesDocument(md.Project, documentReference);

            associatesDocument.GlobalId = "1R7R97$uLAAv4wci$KGwn8";
            IfcMaterial    material = new IfcMaterial(md, "ReinforcingSteel", "", "");
            List <Point3d> points   = new List <Point3d>()
            {
                new Point3d(-69.0, 0.0, -122.0), new Point3d(-69.0, 0.0, -79.0), new Point3d(-54.9411254969541, 0.0, -45.0588745030455), new Point3d(-21.0, 0.0, -31.0), new Point3d(21.0, 0.0, -31.0), new Point3d(54.9411254969541, 0.0, -45.0588745030455), new Point3d(69.0, 0.0, -78.9999999999999), new Point3d(69.0, 0.00000000000000089, -321.0), new Point3d(54.9939785957165, 1.21791490472034, -354.941125496954), new Point3d(21.1804517666074, 4.15822158551252, -369.0), new Point3d(-20.6616529376114, 7.79666547283599, -369.0), new Point3d(-54.4751797667207, 10.7369721536282, -354.941125496954), new Point3d(-68.4812011710042, 11.9548870583485, -321.0), new Point3d(-69.0, 12.0, -79.0), new Point3d(-54.9411254969541, 12.0, -45.0588745030455), new Point3d(-21.0, 12.0, -31.0), new Point3d(21.0, 12.0, -31.0), new Point3d(54.9411254969541, 12.0, -45.0588745030455), new Point3d(69.0, 12.0, -78.9999999999999), new Point3d(69.0, 12.0, -122.0),
            };
            PolyCurve pc = new PolyCurve();

            pc.Append(new Line(points[0], points[1]));
            pc.Append(new Arc(points[1], points[2], points[3]));
            pc.Append(new Line(points[3], points[4]));
            pc.Append(new Arc(points[4], points[5], points[6]));
            pc.Append(new Line(points[6], points[7]));
            pc.Append(new Arc(points[7], points[8], points[9]));
            pc.Append(new Line(points[9], points[10]));
            pc.Append(new Arc(points[10], points[11], points[12]));
            pc.Append(new Line(points[12], points[13]));
            pc.Append(new Arc(points[13], points[14], points[15]));
            pc.Append(new Line(points[15], points[16]));
            pc.Append(new Arc(points[16], points[17], points[18]));
            pc.Append(new Line(points[18], points[19]));
            IfcBoundedCurve directrix = IfcBoundedCurve.ConvertCurve(md, pc);

            double                barDiameter = 12, area = Math.PI * Math.Pow(barDiameter, 2) / 4;
            IfcSweptDiskSolid     sweptDiskSolid     = new IfcSweptDiskSolid(directrix, barDiameter / 2.0, 0);
            IfcRepresentationMap  representationMap  = new IfcRepresentationMap(sweptDiskSolid);
            string                shapeCode          = ""; //Todo
            IfcReinforcingBarType reinforcingBarType = new IfcReinforcingBarType(md, new IfcElemTypeParams("0jMRtfHYXE7u4s_CQ2uVE9", "12 Diameter Ligature", "", "", ""), material, representationMap, null, IfcReinforcingBarTypeEnum.LIGATURE, barDiameter, area, 1150, IfcReinforcingBarSurfaceEnum.TEXTURED, shapeCode, null);

            reinforcingBarType.ObjectTypeOf.GlobalId        = "1iAfl2ERbFmwi7uniy1H7j";
            reinforcingBarType.Material.Associates.GlobalId = "3gfVO40P5EfQyKZ_bF0R$6";
            if (assembly)
            {
                IfcMaterial            concrete            = new IfcMaterial(md, "Concrete", "", "Concrete");
                string                 name                = "400x200RC";
                IfcRectangleProfileDef rectangleProfileDef = new IfcRectangleProfileDef(md, IfcProfileTypeEnum.AREA, name, null, 400, 200);
                IfcMaterialProfile     materialProfile     = new IfcMaterialProfile(md, name, "", concrete, rectangleProfileDef, 0, "");

                IfcBeamType beamType = new IfcBeamType(md, new IfcElemTypeParams("3bdpqVuWTCbxJ2S3ODYv6q", name, "", "", ""), materialProfile, null, IfcBeamTypeEnum.BEAM);
                beamType.ObjectTypeOf.GlobalId        = "2oaQVVf79BrwRouvtRuQVg";
                beamType.Material.Associates.GlobalId = "2ZEgyI2v184hwa$_diRqS9";
                IfcBeamStandardCase beamStandardCase = new IfcBeamStandardCase(building, new IfcElemParams("1yjQ2DwLnCC8k3i3X6D_ut", "", "", "", ""), beamType, new Line(0, 0, 0, 0, 5000, 0), Vector3d.ZAxis, IfcCardinalPointReference.TOPMID, null);
                beamStandardCase.Material.Associates.GlobalId = "3DWeleqqjEG9KshbOZXUdY";
                IfcElementAssembly elementAssembly = new IfcElementAssembly(beamStandardCase, new IfcElemParams("0Q1tCJWdj4kOkZUg7rkf2h", "", "", "", ""), IfcAssemblyPlaceEnum.FACTORY, IfcElementAssemblyTypeEnum.REINFORCEMENT_UNIT);
                List <string>      ids             = new List <string>()
                {
                    "0ohBfsArr3ruXYxacT4yl5", "3YrK7RbE122fNRsP5djFAe", "0wxAc63nj5AezFhfks7wLL", "0bsov2wZL6tRRZmKy4vuUU", "3qrgfIBb92ZegJTle7jou3", "16m6R3JeT83fJPCze2yU$a", "2SGIIYjSbCuu3HVwoLt1yh", "0PsLby6eL8_hVEt4QwK0lZ", "1325VJou5AngWp1djcV0hL", "20zj_$BcH74xRgR4bDrLNb", "3M4SfEMtHEJukgZR4hw$eV", "23BYnIaOLBZPVTrKVEDJiy", "2XulRByDL8ugyo4Uqv9rJr", "2xvQMSga96XOT3VeCS6ZsK", "2gUE6_w3j77f8YJGz_2RMl", "0J0dRL4tT93REAabfASDom", "048RJ151b81PqODsTMD4EA", "3hXx9Kb6b5bvjgr9pwvpz0", "0FmUHg8ZX0ZfY$0f5nkM2l", "2_zvpwRdvAuRiTlHXX$Qp8", "1mhkXHKfX6PxdS2vZn17wX", "0CeIQzUqP5qOOeAjMtH2OX", "3shtoAQL5BAhvwA_1Ph$lC", "22j4RNKqD2IBRDGig5eaCF", "3Wvu6qGJH4ChhTV3pl9CGh", "37Qrf07Iz3tRMbSxEA4ynH", "2gelqZ1Wv8BvCy6TstVGkd", "1Q21dHc_X7eRppCHrT69Vb", "0e6Wc08NLD59ueqCAK1gxp", "3xdMOSZMj3cBOV_QTbXZha", "1r_U9JTkHDWwkv_nfWFHVe", "29I7_S2fT3WRD4zPH4YjmD", "0$ciATTaP17PJMHQD0$N3Y", "1irBeCCUf82wdGg7qTPCbW"
                };
                int jcounter = 0;
                for (int icounter = 25; icounter < 5000; icounter += 150)
                {
                    IfcElemParams ep = new IfcElemParams(ids[jcounter++], "", "", "", "");
                    reinforcingBarType.GenerateMappedItemElement(elementAssembly, new Plane(new Point3d(0, icounter, 0), Vector3d.XAxis, Vector3d.YAxis), ep);
                }
                elementAssembly.IsDecomposedBy[0].GlobalId = "1WdB196Kb72f_pKgj5rklU";
            }
            else
            {
                reinforcingBarType.GenerateMappedItemElement(building, Plane.WorldXY, new IfcElemParams("0WUveBtSTDbunNjDLsuRn$", "", "", "", ""));
            }
        }
Beispiel #11
0
        /// <summary>
        /// Add the data to the Document Information object
        /// </summary>
        /// <param name="row">COBieDocumentRow holding the data</param>
        private void AddDocument(COBieDocumentRow row)
        {
            if (CheckIfExistOnMerge(row))
            {
                return; //already in document
            }
            IfcDocumentInformation   ifcDocumentInformation   = Model.Instances.New <IfcDocumentInformation>();
            IfcRelAssociatesDocument ifcRelAssociatesDocument = Model.Instances.New <IfcRelAssociatesDocument>();

            //Add Created By, Created On and ExtSystem to Owner History.
            SetUserHistory(ifcRelAssociatesDocument, row.ExtSystem, row.CreatedBy, row.CreatedOn);

            if (Contacts.ContainsKey(row.CreatedBy))
            {
                ifcDocumentInformation.DocumentOwner = (IfcPersonAndOrganization)Contacts[row.CreatedBy];
            }

            //using statement will set the Model.OwnerHistoryAddObject to IfcConstructionProductResource.OwnerHistory as OwnerHistoryAddObject is used upon any property changes,
            //then swaps the original OwnerHistoryAddObject back in the dispose, so set any properties within the using statement
            using (COBieXBimEditScope context = new COBieXBimEditScope(Model, ifcRelAssociatesDocument.OwnerHistory))
            {
                //create relationship between Document and ifcObjects it relates too
                ifcRelAssociatesDocument.RelatingDocument = ifcDocumentInformation;
                //Add Name
                if (ValidateString(row.Name))
                {
                    ifcDocumentInformation.Name = row.Name;
                }

                //Add Category
                if (ValidateString(row.Category))
                {
                    ifcDocumentInformation.Purpose = row.Category;
                }

                //Add approved By
                if (ValidateString(row.ApprovalBy))
                {
                    ifcDocumentInformation.IntendedUse = row.ApprovalBy;
                }

                //Add Stage
                if (ValidateString(row.Stage))
                {
                    ifcDocumentInformation.Scope = row.Stage;
                }

                //Add GlobalId
                AddGlobalId(row.ExtIdentifier, ifcRelAssociatesDocument);

                //Add Object Relationship
                IfcRoot ifcRoot = GetObjectRelationship(row);
                //add to the document relationship object
                if (ifcRoot != null)
                {
                    ifcRelAssociatesDocument.RelatedObjects.Add(ifcRoot);
                }


                //Add Document reference
                AddDocumentReference(row, ifcDocumentInformation);

                //add Description
                if (ValidateString(row.Description))
                {
                    ifcDocumentInformation.Description = row.Description;
                }

                //Add Reference
                if (ValidateString(row.Reference))
                {
                    ifcDocumentInformation.DocumentId = row.Reference;
                }
                else
                {
                    ifcDocumentInformation.DocumentId = ""; //required field so add blank string
                }
            }
        }
        public override void Run()
        {
            using (var txn = model.BeginTransaction("Example creation"))
            {
                IfcProject        project           = model.Instances.New <IfcProject>(p => p.Name = "TriluxLightingProducts");
                IfcUnitAssignment ifcUnitAssignment = model.Instances.New <IfcUnitAssignment>(ua =>
                {
                    ua.Units.Add(model.Instances.New <IfcSIUnit>(u =>
                    {
                        u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.LENGTHUNIT;
                        u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.METRE;
                        u.Prefix   = Xbim.Ifc4.Interfaces.IfcSIPrefix.MILLI;
                    }));
                    ua.Units.Add(model.Instances.New <IfcSIUnit>(u =>
                    {
                        u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.MASSUNIT;
                        u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.GRAM;
                        u.Prefix   = Xbim.Ifc4.Interfaces.IfcSIPrefix.KILO;
                    }));
                });

                var ifcClassificationSystemOmniClass = model.Instances.New <IfcClassification>();
                ifcClassificationSystemOmniClass.Name        = "Omniclass";
                ifcClassificationSystemOmniClass.Edition     = "1.0";
                ifcClassificationSystemOmniClass.EditionDate = "2018-12-27T00:00:00.0000000";
                ifcClassificationSystemOmniClass.Description = "The OmniClass Construction Classification System (known as OmniClass™ or OCCS) is a classification system for the construction industry. OmniClass is useful for many applications, from organizing library materials, product literature, and project information, to providing a classification structure for electronic databases. It incorporates other extant systems currently in use as the basis of many of its Tables – MasterFormat™ for work results, UniFormat for elements, and EPIC (Electronic Product Information Cooperation) for structuring products.";
                ifcClassificationSystemOmniClass.Location    = "http://www.omniclass.org/";

                var ifcClassificationReferenceOmniClass = model.Instances.New <IfcClassificationReference>();
                ifcClassificationReferenceOmniClass.Identification   = "23-35-47";
                ifcClassificationReferenceOmniClass.Name             = "Electrical Lighting";
                ifcClassificationReferenceOmniClass.Description      = "NOT PROVIDED";
                ifcClassificationReferenceOmniClass.ReferencedSource = ifcClassificationSystemOmniClass;

                var ifcRelAssociatesClassificationOmniClass = model.Instances.New <IfcRelAssociatesClassification>();
                ifcRelAssociatesClassificationOmniClass.RelatingClassification = ifcClassificationReferenceOmniClass;

                var ifcClassificationSystemUniClass = model.Instances.New <IfcClassification>();
                ifcClassificationSystemUniClass.Name        = "Uniclass";
                ifcClassificationSystemUniClass.Edition     = "2015";
                ifcClassificationSystemUniClass.EditionDate = "";
                ifcClassificationSystemUniClass.Description = "";
                ifcClassificationSystemUniClass.Location    = "https://www.thenbs.com/our-tools/introducing-uniclass-2015";

                var ifcClassificationReferenceUniClass = model.Instances.New <IfcClassificationReference>();
                ifcClassificationReferenceUniClass.Identification   = "CA-70-10-30";
                ifcClassificationReferenceUniClass.Name             = "Site lighting equipment";
                ifcClassificationReferenceUniClass.Description      = "NOT PROVIDED";
                ifcClassificationReferenceUniClass.ReferencedSource = ifcClassificationSystemUniClass;

                var ifcRelAssociatesClassificationUniClass = model.Instances.New <IfcRelAssociatesClassification>();
                ifcRelAssociatesClassificationUniClass.RelatingClassification = ifcClassificationReferenceUniClass;

                //Insert a project library to store the product data templates and type products
                IfcProjectLibrary ifcProductDataLibrary = New <IfcProjectLibrary>(l => {
                    l.Name        = "TriluxLightingProductsLibrary";
                    l.GlobalId    = "1DbshdzGD71ejurQqQcxbw";
                    l.Description = "Library for Trilux light fixtures product data templates based on the ZVEI European core properties";
                    l.Phase       = "Design,Build,Operate";
                });
                Comment(ifcProductDataLibrary, @"Root element of this file. Because this doesn't define a specific instance in the building it is a library. It can be used to declare elements, properties, property templates and other library objects which can be later used in the actual design.");
                Comment(ifcProductDataLibrary.OwnerHistory, @"Owner history is used to define ownership of the information.");

                var ifcProductDataLibraryDeclarations = New <IfcRelDeclares>(rel =>
                {
                    rel.RelatingContext = ifcProductDataLibrary;
                }).RelatedDefinitions;
                Comment(ifcProductDataLibraryDeclarations.OwningEntity, @"This relation points to all definitions declared within the scope of the library. These can be elements, element types, properties or property templates");


                //Creating an IfcPropertySetTemplate manually
                //This is not optimal
                //Instead of creating the IfcPropertySetTemplates manually,
                //they should be loaded from the publishing dictionary

                //Read templates from excel sheet
                var          workbook = new XLWorkbook(Path.Combine(sourceFolder, sourceFile));
                IXLWorksheet worksheetTemplates;
                IXLRange     rangeTemplates;
                worksheetTemplates = workbook.Worksheet("Templates");
                rangeTemplates     = worksheetTemplates.Range("A1:H27");
                IXLTable  rawDataTemplates = rangeTemplates.AsTable();
                DataTable dtTemplates      = ReadDataTable(worksheetTemplates);


                IfcPropertySetTemplate ifcPropertySetTemplate = model.Instances.New <IfcPropertySetTemplate>(pset =>
                {
                    pset.GlobalId         = "1DbshTzGD71ejurQqQcxbw";
                    pset.Name             = "IfcPropertySetTemplate";
                    pset.Description      = "Group of properties for " + ifcProductDataLibrary.Name;
                    pset.ApplicableEntity = "IfcLightFixture/USERDEFINED";
                    pset.TemplateType     = Xbim.Ifc4.Interfaces.IfcPropertySetTemplateTypeEnum.PSET_TYPEDRIVENONLY;
                });
                Comment(ifcPropertySetTemplate, @"Declaration of 'IfcPropertySetTemplate' within the library for lighting product data templates.");
                Comment(ifcPropertySetTemplate, @"Insert property templates; they should be loaded from the publishing dictionary");

                foreach (DataRow row in dtTemplates.Rows)
                {
                    //Publisher SystemName  GlobalId PrimaryMeasureType  DataColumn

                    ifcPropertySetTemplate.HasPropertyTemplates.AddRange(new[]
                    {
                        model.Instances.New <IfcSimplePropertyTemplate>(pt =>
                        {
                            pt.Name               = row["SystemName"].ToString();
                            pt.Description        = "";
                            pt.GlobalId           = row["GlobalId"].ToString();
                            pt.TemplateType       = Xbim.Ifc4.Interfaces.IfcSimplePropertyTemplateTypeEnum.P_SINGLEVALUE;
                            pt.AccessState        = Xbim.Ifc4.Interfaces.IfcStateEnum.LOCKED;
                            pt.PrimaryMeasureType = row["PrimaryMeasureType"].ToString();

                            string primaryMeasureType = row["PrimaryMeasureType"].ToString();

                            if (primaryMeasureType == typeof(IfcLengthMeasure).Name)
                            {
                                pt.PrimaryUnit = model.Instances.New <IfcSIUnit>(u =>
                                {
                                    u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.LENGTHUNIT;
                                    u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.METRE;
                                    u.Prefix   = Xbim.Ifc4.Interfaces.IfcSIPrefix.MILLI;
                                });
                            }
                            else if (primaryMeasureType == typeof(IfcMassMeasure).Name)
                            {
                                pt.PrimaryUnit = model.Instances.New <IfcSIUnit>(u =>
                                {
                                    u.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.MASSUNIT;
                                    u.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.GRAM;
                                });
                            }
                            else if (primaryMeasureType == typeof(IfcPlaneAngleMeasure).Name)
                            {
                                pt.PrimaryUnit = model.Instances.New <IfcConversionBasedUnit>(punit =>
                                {
                                    //Convert the angel measure from the unit grad to the SI Unit radian
                                    //rad=grad*(PI/180)
                                    punit.Name             = "Grad";
                                    punit.UnitType         = Xbim.Ifc4.Interfaces.IfcUnitEnum.PLANEANGLEUNIT;
                                    punit.ConversionFactor = model.Instances.New <IfcMeasureWithUnit>(mwu =>
                                    {
                                        mwu.UnitComponent = model.Instances.New <IfcSIUnit>(siUnit =>
                                        {
                                            siUnit.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.PLANEANGLEUNIT;
                                            siUnit.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.RADIAN;
                                        });
                                        mwu.ValueComponent = new IfcReal(Math.PI / 180);
                                    });
                                    punit.Dimensions = model.Instances.New <IfcDimensionalExponents>(dim =>
                                    {
                                        dim.LengthExponent                   = 0;
                                        dim.MassExponent                     = 0;
                                        dim.TimeExponent                     = 0;
                                        dim.ElectricCurrentExponent          = 0;
                                        dim.ThermodynamicTemperatureExponent = 0;
                                        dim.AmountOfSubstanceExponent        = 0;
                                        dim.LuminousIntensityExponent        = 0;
                                    });
                                });
                            }
                        })
                    });
                }
                ;


                ifcProductDataLibraryDeclarations.Add(ifcPropertySetTemplate);

                //Read source data from excel sheet
                var          workbookData = new XLWorkbook(Path.Combine(sourceFolder, sourceFile));
                IXLWorksheet worksheetData;
                IXLRange     rangeData;
                worksheetData = workbookData.Worksheet("Sheets");
                rangeData     = worksheetData.Range("A1:Z690");
                IXLTable  rawData = rangeData.AsTable();
                DataTable dtData  = ReadDataTable(worksheetData);

                var ifcRelDefinesByTemplate = New <IfcRelDefinesByTemplate>(dbt =>
                {
                    dbt.RelatingTemplate = ifcPropertySetTemplate;
                });

                int n = 0;
                do
                {
                    foreach (DataRow row in dtData.Rows)
                    {
                        var ifcTypeProduct = model.Instances.New <IfcTypeProduct>();
                        ifcTypeProduct.GlobalId             = "1DbshTzGD71ejurQqQcxbw"; //How to generate a fresh IFC GlobalId with XBim?
                        ifcTypeProduct.Name                 = row["Name"].ToString();
                        ifcTypeProduct.Description          = "Description of " + ifcTypeProduct.Name;
                        ifcTypeProduct.ApplicableOccurrence = "IfcLightFixture";

                        ifcRelAssociatesClassificationOmniClass.RelatedObjects.Add(ifcTypeProduct);
                        ifcRelAssociatesClassificationUniClass.RelatedObjects.Add(ifcTypeProduct);

                        IfcPropertySet ifcPropertySet = model.Instances.New <IfcPropertySet>(pset =>
                        {
                            pset.Name = "Properties of " + ifcTypeProduct.Name;
                        });

                        foreach (DataRow template in dtTemplates.Rows)
                        {
                            if (template["PropertyWithDocumentLink"].ToString() == "Yes")
                            {
                                //Insert the product information into documents
                                string folderName = template["SystemName"].ToString();
                                string docName    = row[template["SystemName"].ToString()].ToString();

                                IfcDocumentInformation ifcDocumentInformation = model.Instances.New <IfcDocumentInformation>(doc =>
                                {
                                    doc.Identification   = docName;
                                    doc.Name             = docName;
                                    doc.Location         = $@"{folderName}/{docName}";
                                    doc.Confidentiality  = Xbim.Ifc4.Interfaces.IfcDocumentConfidentialityEnum.PUBLIC;
                                    doc.ElectronicFormat = MimeTypes.GetMimeType(docName);
                                    doc.IntendedUse      = "Product information";
                                    doc.Purpose          = "Product information";
                                });

                                IfcRelAssociatesDocument ifcRelAssociatesDocument = model.Instances.New <IfcRelAssociatesDocument>(docref =>
                                {
                                    docref.RelatedObjects.Add(ifcTypeProduct);
                                    docref.RelatingDocument = ifcDocumentInformation;
                                });

                                //<IfcRelAssociatesDocument GlobalId="3vBcwkKGf1cxmQZUtNnL0g">
                                //   < RelatedObjects >
                                //      < IfcTransportElement xsi: nil = "true" ref= "i143" />
                                //   </ RelatedObjects >
                                //   < RelatingDocument >
                                //      < IfcDocumentInformation xsi: nil = "true" ref= "i150" />
                                //   </ RelatingDocument >
                                //</ IfcRelAssociatesDocument >
                            }
                            else
                            {
                                //Insert the product information into Properties
                                ifcPropertySet.HasProperties.AddRange(new[]
                                {
                                    model.Instances.New <IfcPropertySingleValue>(p =>
                                    {
                                        string propertyName = template["SystemName"].ToString();
                                        var dataValue       = row[propertyName];

                                        p.Name        = propertyName;
                                        p.Description = "";

                                        string primaryMeasureType = template["PrimaryMeasureType"].ToString();
                                        if (primaryMeasureType == typeof(IfcLengthMeasure).Name)
                                        {
                                            p.NominalValue = new IfcMassMeasure(Double.Parse(dataValue.ToString()));
                                        }
                                        else if (primaryMeasureType == typeof(IfcMassMeasure).Name)
                                        {
                                            p.NominalValue = new IfcMassMeasure(Double.Parse(dataValue.ToString()));
                                        }
                                        else if (primaryMeasureType == typeof(IfcPlaneAngleMeasure).Name)
                                        {
                                            p.NominalValue = new IfcPlaneAngleMeasure(Double.Parse(dataValue.ToString()));
                                        }
                                        else
                                        {
                                            p.NominalValue = new IfcLabel(dataValue.ToString());
                                        }
                                    })
                                });
                            }
                        }
                        ;

                        ifcTypeProduct.HasPropertySets.Add(ifcPropertySet);

                        ifcProductDataLibraryDeclarations.Add(ifcTypeProduct);
                        Comment(ifcTypeProduct, @"Declaration of 'IfcTypeProduct' within the library for a ligthing product.");

                        ifcRelDefinesByTemplate.RelatedPropertySets.Add(ifcPropertySet);
                    }
                    n++;
                }while (n < 1);

                txn.Commit();
            }

            string targetFileName = Path.Combine(targetFolder, targetFile);

            SaveAs(targetFileName, true, typeof(IfcProjectLibrary));

            //Create ifcZip file
            File.Delete(zipFile);
            ZipFile.CreateFromDirectory(sourceFolder, zipFile);
            using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Update))
            {
                zipArchive.GetEntry(sourceFile).Delete();
                zipArchive.CreateEntryFromFile($"{targetFolder}/{targetFile}.ifcXML", $"{targetFile}.ifcXML");
                zipArchive.CreateEntryFromFile($"{targetFolder}/{targetFile}.ifc", $"{targetFile}.ifc");
            }
        }